如何使用linq和xpath从xml中获取字符串列表的值?

时间:2015-12-15 15:45:55

标签: c# xml linq xpath

我有以下列表

List<string> vehicles = new List<string> {"Year", "Make", "Model" };

我正在使用

从巨大的xml中获取节点<Vehicle>
var vehicle = xdoc.XPathSelectElements("s0:Transport/s0:Vehicles/s0:Vehicle[s0:Insured='Y']", namespaceManager).ToList();

我正试图从车辆节点获得年份,制造和模型:

var vehicleList = vehicle.Where(x => vehicles.Contains(x.Name.LocalName)).ToList();

但它会为null返回vehicleList值。有谁可以请更正我的查询?

Xml样本

 <Transport>
 .....
 <Vehicles>
      <Vehicle>
        <Insured>Y</Insured>
        <Number>1</Number>
        <Year>1997</Year>
        <ComprehensiveSymbol />
        <Make>FORD</Make>
        <Model>F-250 HEAVY DUTY</Model>
        <BodyStyle>PICKUP</BodyStyle>
        <VehicleType>C</VehicleType>
        <UseType>
          <V4Code i:nil="true" />
          <SourceCode>1</SourceCode>
          -----

     </Vehicle>
</Vehicles>

---
--
</Transport>

1 个答案:

答案 0 :(得分:1)

如果我理解正确,那么我会用LINQ-to-XML代替你: -

XDocument xdoc = XDocument.Load("XMLFile");
var vehicleList = xdoc.Root.Descendants("Vehicle")
                                       .Where(x => (string)x.Element("Insured") == "Y")
                                       .Elements()
                                       .Where(x => vehicles.Any(z => z == x.Name));

这将返回IEnumerable<XElement>,您可以使用foreach循环进行迭代。此外,如果您想直接检索该值,那么您可以像这样投影值(最后) - .Select(x => (string)x)将返回IEnumerable<string>