c#解析XML问题

时间:2011-10-04 13:18:40

标签: c# .net xml silverlight xml-serialization

我正在使用此代码尝试阅读下面的这个XML,但是在foreach循环中没有读取任何内容并跳过它。感谢。

C#

 XElement _xml;
 _xml = XElement.Parse(PostResult);
 foreach (XElement value in _xml.Elements("ServiceDelivery")
                                .Element("StopMonitoringDelivery")
                                .Elements("MonitoredStopVisit"))
          {
             StopFeed _item = new StopFeed();
             _item.A= value.Element("PublishedLineName").Value;
             _item.B = value.Element("DirectionName").Value;

              listBox1.Items.Add(_item);
           }

XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>    
<Siri version="1.0" xmlns="http://www.siri.org.uk/">
<ServiceDelivery>
    <ResponseTimestamp>2011-10-04T11:45:36.415+01:00</ResponseTimestamp>
    <ResponseMessageIdentifier>1d8bc237-2df6-43e6-af56-c750d3089eb6</ResponseMessageIdentifier>
    <StopMonitoringDelivery version="1.0">
        <ResponseTimestamp>2011-10-04T11:45:36.415+01:00</ResponseTimestamp>
        <RequestMessageRef>1</RequestMessageRef>
        <MonitoredStopVisit>
            <RecordedAtTime>2011-10-04T11:45:36.412+01:00</RecordedAtTime>
            <MonitoringRef>020035057</MonitoringRef>
            <MonitoredVehicleJourney>
                <FramedVehicleJourneyRef>
                    <DataFrameRef>-</DataFrameRef>
                    <DatedVehicleJourneyRef>-</DatedVehicleJourneyRef>
                </FramedVehicleJourneyRef>
                <VehicleMode>bus</VehicleMode>
                <PublishedLineName>28</PublishedLineName>
                <DirectionName>blahblah</DirectionName>
                <OperatorRef>153</OperatorRef>
                <MonitoredCall>
                    <AimedDepartureTime>2011-10- 04T11:48:00.000+01:00</AimedDepartureTime>
                </MonitoredCall>
            </MonitoredVehicleJourney>
        </MonitoredStopVisit>
    </StopMonitoringDelivery>
</ServiceDelivery>
</Siri>

3 个答案:

答案 0 :(得分:4)

我认为您忘记了命名空间。看看XNamespace

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

foreach (XElement value in _xml.Elements(xn+ "ServiceDelivery")
                            .Element(xn+ "StopMonitoringDelivery")
                            .Elements(xn+ "MonitoredStopVisit"))
{
      ....
}

答案 1 :(得分:1)

根元素是Siri。

使用:

XElement value in _xml.Root.Elements("ServiceDelivery")
                            .Element("StopMonitoringDelivery")
                            .Elements("MonitoredStopVisit"))

XElement value in _xml.Element("Siri")
                            .Elements("ServiceDelivery")
                            .Element("StopMonitoringDelivery")
                            .Elements("MonitoredStopVisit"))

/ B

答案 2 :(得分:0)

尝试_xml.Elements("//ServiceDelivery")_xml.Elements("Siri/ServiceDelivery"),您忘记了ServiceDelivery节点是Siri节点的子节点。

或者XML名称空间可能是问题,请查看此page并查看如何使用XmlNamespaceManager