2013-03-21 38 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