我有以下XDocument
<results>
<team id="1" name="Manchester United">
<player name="Ryan Giggs" position="midfielder" />
<player name="Wayne Rooney" position="striker" />
<player name="Rio Ferdinand" position="defender" />
</team>
<team id="2" name="Liverpool">
<player name="Steven Gerrard" position="midfielder" />
<player name="Luis Suarez" position="striker" />
<player name="John Terry" position="defender" />
</team>
<team id="1" name="Manchester City">
<player name="Kolo Toure" position="midfielder" />
<player name="Samuel Eto" position="striker" />
<player name="Vincent Company" position="defender" />
</team>
</results>
我希望得到以下所有数据
IEnumerable<Teams> (TeamID and TeamName)
IEnumerable<PLayers> (TeamID, PlayerName, Position)
目前我有以下
XElement results = doc.Root.Element("results");
var teams =
(from p in results.Descendants("team")
select new
{
Id = utils.GetDecimal(p.Element("id").Value),
TeamName = p.Element("name")
}).ToList();
然而,这是一个错误。
然后我的想法是为每个团队做同样的事情,并让团队的球员。
我有什么不对?
答案 0 :(得分:0)
id
不是元素,而是属性Value
属性,如果找不到该元素,则会抛出异常,而是使用显式强制转换。还为您的团队和玩家创建一个课程,而不是创建匿名类型。
var teams = (from p in results.Descendants("team")
select new
{
Id = utils.GetDecimal((string)p.Attribute("id")),
TeamName = (string)p.Element("name"),
Players = p.Elements("player")
.Select(x => new
{
Name = (string)x.Attribute("name"),
Position = (string)x.Attribute("position")
})
.ToList()
}).ToList();