0

我正在使用 c# 执行 HttpWebrequest。我得到以下回复

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Siri version="1.0" xmlns="http://www.siri.org.uk/">
  <ServiceDelivery>
    <ResponseTimestamp>2013-03-21T11:40:13.514Z</ResponseTimestamp>
    <StopMonitoringDelivery version="1.0">
      <ResponseTimestamp>2013-03-21T11:40:13.514Z</ResponseTimestamp>
      <RequestMessageRef>12345</RequestMessageRef>
      <MonitoredStopVisit>
        <RecordedAtTime>2013-03-21T11:40:13.514Z</RecordedAtTime>
        <MonitoringRef>020035811</MonitoringRef>
        <MonitoredVehicleJourney>
          <FramedVehicleJourneyRef>
            <DataFrameRef>-</DataFrameRef>
            <DatedVehicleJourneyRef>-</DatedVehicleJourneyRef>
          </FramedVehicleJourneyRef>
          <VehicleMode>bus</VehicleMode>
          <PublishedLineName>1</PublishedLineName>
          <DirectionName>Kempston</DirectionName>
          <OperatorRef>STB</OperatorRef>
          <MonitoredCall>
            <AimedDepartureTime>2013-03-21T11:41:00.000Z</AimedDepartureTime>
            <ExpectedDepartureTime>2013-03-21T11:44:27.000Z</ExpectedDepartureTime>
          </MonitoredCall>
        </MonitoredVehicleJourney>
      </MonitoredStopVisit>
    </StopMonitoringDelivery>
  </ServiceDelivery>
</Siri>

此响应保存在名为“ResponseFromServer”的字符串变量中现在我只想在列表框中显示“ExpectedDepartureTime”

我尝试使用以下代码执行此操作:

//XMLResponse put in documentRoot
            XDocument documentRoot = XDocument.Parse(responseFromServer);

            //Linq To XML
            var documents =
            (from docs in documentRoot.Descendants("ServiceDelivery").Descendants("StopMonitoringDelivery").Descendants("MonitoredStopVisit").Descendants("MonitoredVehicleJourney").Descendants("MonitoredCall")
             select new
             {
                 dep = docs.Element("ExpectedDepartureTime").Value
             });
            //Show every ExpectedDepartureTime
            foreach (var i in documents)
            {
            lstHours.Items.Add(i);

                MessageBox.Show(i.ToString());
            }

当我尝试这个时,什么也没有发生(消息框没有出现,在列表框中我看不到任何东西)。我也尝试先标记后裔但没有成功...

有人可以帮我解决这个问题吗?

谢谢!

4

1 回答 1

1

您需要像这样指定命名空间,然后使用一种方法Descendants

XNamespace ns = "http://www.siri.org.uk/";

var documents = 
         documentRoot.Descendants(ns + "MonitoredCall")
                     .Select(x => x.Element(ns + "ExpectedDepartureTime").Value);

现在你可以

foreach (var i in documents)
{
      lstHours.Items.Add(i);

      MessageBox.Show(i.ToString());
}

印刷

2013-03-21T11:44:27.000Z
于 2013-03-21T16:11:25.940 回答