C# 如何获取列表<;XElement>;从这个XML?
我有一个类似于以下内容的XML块:C# 如何获取列表<;XElement>;从这个XML?,c#,xml,linq-to-xml,C#,Xml,Linq To Xml,我有一个类似于以下内容的XML块: <factsheet> <bilcontents > <config name="1" /> </bilcontents> <singlefactsheet includeInBook="true"> <config name="7" /> <fund id="630" /> </singlefactsheet> <doubleFactshee
<factsheet>
<bilcontents >
<config name="1" />
</bilcontents>
<singlefactsheet includeInBook="true">
<config name="7" />
<fund id="630" />
</singlefactsheet>
<doubleFactsheet includeInBook="true">
<config name="8" />
<fund id="623" />
<fund id="624" />
</doubleFactsheet>
<tripplefactsheet includeInBook="true">
<config name="6" />
<fund id="36" />
<fund id="37" />
<fund id="38" />
</tripplefactsheet>
</factsheet>
我是否有可能获得包含这些元素的元素列表,只要includeInBook=“true”
,然后根据节点类型处理每个元素。绝对:
var list = doc.Root
.Elements()
.Where(x => (bool?) x.Attribute("includeInBook") == true)
.ToList();
顺便说一句,处理可为空的布尔值可能有点奇怪。lambda表达式的另一种方法可能是:
x => (bool?) x.Attribute("includeInBook") ?? false
或
这就是我所做的,尽管乔恩几乎击败了我
var inBook = nodes.Descendants()
.Where(xx => xx.Attribute("includeInBook") != null)
.Select(xx => xx).ToList();
或者,您可以使用内置的XPath扩展方法(它们位于
System.Xml.XPath
:
XDocument doc;
// ...
var includeInBook = doc.XPathSelectElements("/factsheet/*[@includeInBook = 'true']")
改为:
:选择元素“factsheet”/factsheet
:然后选择所有子项/*
:将方括号读作“where”[…]
:属性“includeInBook”的内容等于'true'@includeInBook='true'
应考虑为XML创建数据结构,并使用“序列化”这将是一个更干净的方式来与这个数据模型交互。只是一些要考虑的事情……谢谢乔恩,我实际上自己设计了一些类似的东西,所以我把它放在下面。这只是验证属性是否存在——如果包含“代码>包含书”=“false”。元素肯定不是您想要的。还要注意,
Select
调用是多余的。
XDocument doc;
// ...
var includeInBook = doc.XPathSelectElements("/factsheet/*[@includeInBook = 'true']")