LINQ to XML 如何获取根的 child 然后是后代?
LINQ to XML how to get the child of the root and then descendents?
我有一个 XML 架构定义如下:
<PeopleContainer>
<People>
<Person Name="John Doe" Age="27" CauseOfAwesome="King of All Cosmos" />
<Person Name="Ally McBeagle" Age="7" CauseOfAwesome="Adorable" />
<Person Name="Bender Rodriguez" Age"249" CauseOfAwesome="Bending" />
</People>
</PeopleContainer
我想要做的是将 People 标签作为 IEnumerable
获取,以便我可以将其通过管道传输到我的应用程序中,但我还没有看到针对这种情况的选项。
我一直在尝试这样的事情:
XDocument xdoc = XDocument.Load(path);
var people = from p in xdoc.Descendants("People")
select new
{
Name = p.Attribute("Name").Value,
Age = p.Attribute("Age").Value,
CauseOfAwesome = p.Attribute("CauseOfAwesome")
};
foreach (var p in people)
{
Console.WriteLine(p);
}
我想我可能 people
实例化不正确...
您忘记设置元素人:
var people = from p in xdoc.Root.Descendants("People")
select new
{
Name = p.Element("Person").Attribute("Name").Value,
Age = p.Element("Person").Attribute("Age").Value,
CauseOfAwesome = p.Element("Person").Attribute("CauseOfAwesome")
};
foreach (var n in people)
{
Console.WriteLine(n.Name);
Console.WriteLine(n.Age);
Console.WriteLine(n.CauseOfAwesome);
}
我有一个 XML 架构定义如下:
<PeopleContainer>
<People>
<Person Name="John Doe" Age="27" CauseOfAwesome="King of All Cosmos" />
<Person Name="Ally McBeagle" Age="7" CauseOfAwesome="Adorable" />
<Person Name="Bender Rodriguez" Age"249" CauseOfAwesome="Bending" />
</People>
</PeopleContainer
我想要做的是将 People 标签作为 IEnumerable
获取,以便我可以将其通过管道传输到我的应用程序中,但我还没有看到针对这种情况的选项。
我一直在尝试这样的事情:
XDocument xdoc = XDocument.Load(path);
var people = from p in xdoc.Descendants("People")
select new
{
Name = p.Attribute("Name").Value,
Age = p.Attribute("Age").Value,
CauseOfAwesome = p.Attribute("CauseOfAwesome")
};
foreach (var p in people)
{
Console.WriteLine(p);
}
我想我可能 people
实例化不正确...
您忘记设置元素人:
var people = from p in xdoc.Root.Descendants("People")
select new
{
Name = p.Element("Person").Attribute("Name").Value,
Age = p.Element("Person").Attribute("Age").Value,
CauseOfAwesome = p.Element("Person").Attribute("CauseOfAwesome")
};
foreach (var n in people)
{
Console.WriteLine(n.Name);
Console.WriteLine(n.Age);
Console.WriteLine(n.CauseOfAwesome);
}