2013-03-21 41 views
0

我正在通过使用c#来执行HttpWebrequest。我得到如下回应XMLResponse元素显示在列表中

<?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)。我也尝试Descendant第一个标签没有成功...

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

谢谢!

回答

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 
+0

事实证明,使用XPath名称空间是起初比我怀疑的更复杂一点。它可以完成,但它不像你的解决方案那么简洁。 +1 – 2013-03-21 16:33:52

+0

谢谢,感谢您的回复。 'LINQ to XML'是处理XML的好工具。 – 2013-03-21 16:35:02

+0

是的。命名空间从来没有工作的乐趣。 – 2013-03-21 16:49:56