XMLResponse元素显示在列表中

时间:2013-03-21 16:07:06

标签: c# xml linq linq-to-xml

我正在使用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());
            }

当我尝试时,没有任何事情发生(消息框没有出现,在列表框中我看到nothnig)。我也试着先后标签没有成功...

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

谢谢!

1 个答案:

答案 0 :(得分: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