2013-03-21 9 views
0

C#을 사용하여 HttpWebrequest를하고 있습니다. 나는XMLResponse 요소가 목록에 표시됩니다.

나는 다음과 같이이 작업을 수행하려고이 응답은 지금 난 그냥 목록 상자에서 'ExpectedDepartureTime'을 보여주고 싶다 "ResponseFromServer"라는 문자열 변수에 저장됩니다

<?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> 

다음과 같은 응답을 얻을 코드 :

//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 –

+0

감사합니다. 귀하의 회신에 감사드립니다. 'LINQ to XML'은 xml 처리를위한 아주 좋은 도구입니다. –

+0

예. 네임 스페이스는 절대 재미가 없습니다. –

관련 문제