这是我得到的示例XML:

<ArrayOfService >
  <Service z:Id="i1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
          <primaryUrl>http://www.buses.co.uk/1A</primaryUrl>
          <relativePosition>2</relativePosition>
          <serviceDescription>Whitehawk - County Hospital - City Centre - Hove - Portslade - Mile Oak</serviceDescription>
          <serviceId>1150</serviceId>
          <serviceName>1A</serviceName>
          <serviceNotes />
          <serviceText>Whitehawk - Mile Oak</serviceText>
          <serviceUrls />
     </Service>
</ArrayOfService>


这是代码:

XDocument loadedData = XDocument.Load("services.xml");
//XNamespace ns = "http://schemas.datacontract.org/2004/07/BusExpress.ClassLibrary";

var list = (from item in loadedData.Descendants("ArrayOfService").Descendants("Service")
            where (string)item.Element("serviceName") == "1A"
            select (string)item.Element("serviceId")).FirstOrDefault();


结果显示为null,这为什么呢?

最佳答案

loadedData.Descendants("ArrayOfService")应该是loadedData.Root

有关详细信息,请参见XDocument.Root (MSDN)

10-06 12:06