我有XML描述这样的一些数据:
<People>
<Person>
<Name>Alice</Name>
<Dogs>
<Dog>Labrador</Dog>
<Dog>German Shepherd</Dog>
</Dogs>
</Person>
<Person>
<Name>Bob</Name>
<Dogs>
<Dog>Poodle</Dog>
</Dogs>
</Person>
</People>
还有一些课程:
class Person
{
public string Name { get; set; }
public List<Dog> Dogs { get; set; }
}
class Dogs
{
public string Type { get; set; }
}
我想使用linq to XML来查询这些数据,这样我就可以为每个填充的人创建一组带有Dog集合的Person对象。我该怎么做呢?类似的东西:
var doc = XDocument.Load("Test.xml");
var enumerableOfPeople = from u in doc.Root.Descendants("Person")
select new Person() { Name = u.Element("Name").Value,
Dogs = /* WHAT GOES HERE */ };
答案 0 :(得分:2)
这将填充狗:
var enumerableOfPeople = from u in doc.Root.Descendants("Person")
select new Person()
{
Name = u.Element("Name").Value,
Dogs = (from d in u.Element("Dogs").Descendants("Dog")
select new Dog() { Type = d.Value }).ToList()
};
答案 1 :(得分:1)
var enumerableOfPeople = doc.Root.Descendants("Person")
.Select(u => new Person {
Name = u.Element("Name").Value,
Dogs = u.Descendants().Select(x => new Dog{ Type = x.Value}).ToList()
});
答案 2 :(得分:1)
lambda
获取人员的方法:
var peeps = doc.Root.Descendants("Person").Select(r => new Person()
{
Name = r.Element("Name").Value,
Dogs = r.Element("Dogs").Descendants("Dog").Select(t => new Dog()
{
Type = t.Value
}).ToList()
});