【发布时间】:2016-02-10 18:50:14
【问题描述】:
如何使用 LINQToXml 创建我想要的列表?
到目前为止,我对这两种尝试都很接近。
我应该能够做到这一点而无需创建单独的查询,对吗?
这是我的 XML:
<main>
<cars>
<car name="Honda">
<feature door="4" name="Accord" />
<feature door="2" name="Civic"/>
<feature door="4" name="CRV"/>
</car>
<car name="Ford"/>
<car name="Kia"/>
<car name="Subaru">
<feature door="4" name="Outback"/>
<feature door="4" name="Legacy"/>
</car>
</cars>
</main>
尝试 #1
var listCars = (from c in doc.Root.Descendants("cars")
select new Car
{
Model = (p.Element("car") != null) ? p.Element("car").Attribute("name").Value : null,
Door = (p.Element("car") != null) ? p.Element("car").Attribute("door").Value : null,
Name = p.Attribute("name").Value
}).ToList();
尝试 #2
var cars = from c in doc.Root.Descendants("cars")
select c;
var listPermissions = (from c in cars.Descendants("car")
let cName = p.Parent.Attribute("name").Value
select new Car
{
Model = p.Attribute("name").Value,
Door = p.Attribute("door").Value,
Name = pgn
}).ToList();
我要做的是创建一个看起来像这样的汽车列表:
【问题讨论】:
-
让
Car包含门和名称列表不是更容易吗?而不是尝试将其全部展平?
标签: linq c#-4.0 linq-to-xml