我有以下列表
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>
答案 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>
。