0

我正在使用 API 并以 XML 格式检索数据。这是我的 XML:

<RTT>
  <AgencyList>
    <Agency Name="Caltrain" HasDirection="True" Mode="Rail">
      <RouteList>
        <Route Name="BABY BULLET" Code="BABY BULLET">
          <RouteDirectionList>
            <RouteDirection Code="SB2" Name="SOUTHBOUND TO TAMIEN">
              <StopList>
                <Stop name="Sunnyvale Caltrain Station" StopCode="70222">
                  <DepartureTimeList/>
                </Stop>
              </StopList>
            </RouteDirection>
            <RouteDirection Code="NB" Name="NORTHBOUND TO SAN FRANCISCO">
              <StopList>
                <Stop name="Sunnyvale Caltrain Station" StopCode="70221">
                  <DepartureTimeList>
                    <DepartureTime>69</DepartureTime>
                  </DepartureTimeList>
                </Stop>
              </StopList>
            </RouteDirection>
          </RouteDirectionList>
        </Route>
        <Route Name="LIMITED" Code="LIMITED">...</Route>
        <Route Name="LOCAL" Code="LOCAL">...</Route>
      </RouteList>
    </Agency>
  </AgencyList>
</RTT>

不是每个 DepartureTimeList 都会有一个 DepartureTime 子节点。到目前为止,这是我得到的,它检索 Route 名称:

List<string> trainType = new List<string>();
XDocument doc = XDocument.Load("http://services.my511.org/Transit2.0/GetNextDeparturesByStopName.aspx?token=0f01ac4a-bc16-46a5-8527-5abc79fee435&agencyName=Caltrain&stopName=" + DropDownList1.SelectedItem.Text.ToString());
doc.Save("times.xml");
string feed = doc.ToString();


XmlReader r = XmlReader.Create(new StringReader(feed));
r.ReadToFollowing("RouteList");
if (r.ReadToDescendant("Route"))
{
    do
    {
        trainType.Add(r.GetAttribute("Name"));
    } while (r.ReadToNextSibling("Route"));
}

我最感兴趣的是出发时间(如果存在的话),我整个下午都在努力尝试解析它。

4

1 回答 1

2

试试这个......希望这会做到。

    XmlDocument doc = new XmlDocument();
    doc.Load("xml path");
    XmlNode node = doc.SelectSingleNode("/RTT");
    foreach (XmlNode nodes in node.SelectNodes(
        "/AgencyList/Agency Name/RouteList/Route"))
    {
        trainType.Add(r.GetAttribute("Name"));
        XmlNode s = nodes.SelectSingleNode("Route Name/RouteDirectionList/RouteDirection Code/StopList/Stop");
        if (s != null && s["DepartureTimeList"].HasChildNodes)
        {
            // do stuff here
        }
    }
于 2013-11-03T22:11:13.297 回答