LINQ to XML 选择子元素
我正在尝试使用 LINQ to XML 将 XML 文件中的信息提取到对象中。虽然我可以返回文档和部分 Id 属性,但我无法访问每个部分元素的项目,但它返回文档中所有项目的 IEnumerable。我知道这是正确的,因为我正在调用后代,但我正在努力让它只返回每个部分元素的子项。有人可以帮忙吗?
XML 文档
<root>
<document id="1">
<section id="1.1">
<item id="1.1.1"></item>
<item id="1.1.2"></item>
<item id="1.1.3"></item>
</section>
<section id="1.2">
<item id="1.2.1"></item>
<item id="1.2.2"></item>
</section>
</document>
</root>
LINQ 查询
XElement documentRoot = XElement.Load("document.xml");
var documents = (from docs in documentRoot.Descendants("document")
select new
{
Id = (string) docs.Attribute("id"),
Sections = docs.Elements("section"),
Items = docs.Elements("section").Elements("item")
}).ToList();
foreach(var doc in documents)
{
foreach(var section in doc.Sections)
{
Console.WriteLine("SectionId: " + section.Attribute("Id"));
foreach(var item in doc.Items)
{
Console.WriteLine("ItemId: " + section.Attribute("Id"));
}
}
}
I am trying to extract information from an XML file into an object using LINQ to XML. Although I can return the document and section Id attributes I cannot get access to the Items for each section element, it returns an IEnumerable of all the items in the document. I know this is correct as I’m calling Descendants but am struggling to get it to return only the child items of each section element. Can anybody help?
XML Document
<root>
<document id="1">
<section id="1.1">
<item id="1.1.1"></item>
<item id="1.1.2"></item>
<item id="1.1.3"></item>
</section>
<section id="1.2">
<item id="1.2.1"></item>
<item id="1.2.2"></item>
</section>
</document>
</root>
LINQ Query
XElement documentRoot = XElement.Load("document.xml");
var documents = (from docs in documentRoot.Descendants("document")
select new
{
Id = (string) docs.Attribute("id"),
Sections = docs.Elements("section"),
Items = docs.Elements("section").Elements("item")
}).ToList();
foreach(var doc in documents)
{
foreach(var section in doc.Sections)
{
Console.WriteLine("SectionId: " + section.Attribute("Id"));
foreach(var item in doc.Items)
{
Console.WriteLine("ItemId: " + section.Attribute("Id"));
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在属性
Id
和项目循环上遇到了一些小拼写错误。但是,如果您尝试将所有部分项目放入该项目集合中,那么您在设计级别上就错了,因为Items
应该是Section
属性,而不是Document
(因此您需要查询 XML 两次)。或者,您可以执行以下操作:
输出:
You got some small typos, on attribute
Id
and at item loop. But if you're trying to get all section items into that items collection, you're wrong at design level, asItems
should be aSection
property, notDocument
(so you'll need to query your XML twice).Or, you can to do something like:
Output:
你想要一个扁平结构吗?!?! (来自 LinqPad)
这提供了 2 个
SectionId
项,其中包含具有相关项的XElement
。Do you want a flat structure ?!?! (from LinqPad)
This gives 2
SectionId
items that containesXElement
s with related items.