如何从这个XML获取List <xelement>?</xelement>

时间:2010-06-23 16:27:58

标签: c# xml linq-to-xml

我有一个类似于以下内容的XML块:

<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>

我是否有可能获得包含每个元素的XElements列表,只要includeInBook="true",然后我可以根据节点的类型处理每个元素。

4 个答案:

答案 0 :(得分:2)

绝对:

 var list = doc.Root
               .Elements()
               .Where(x => (bool?) x.Attribute("includeInBook") == true)
               .ToList();

处理可空的布尔可能有点奇怪,顺便说一下。 lambda表达式的另一种方法可能是:

x => (bool?) x.Attribute("includeInBook") ?? false

x => (string) x.Attribute("includeInBook") == "true"

答案 1 :(得分:0)

这就是我解决的问题,尽管Jon几乎打败了我,但

var inBook = nodes.Descendants()
    .Where(xx => xx.Attribute("includeInBook") != null)
    .Select(xx => xx).ToList();

答案 2 :(得分:0)

或者,您可以使用内置的XPath扩展方法方法(它们位于System.Xml.Xpath

XDocument doc;
// ...
var includeInBook = doc.XPathSelectElements("/factsheet/*[@includeInBook = 'true']")

读作:

  • /factsheet:选择元素'factheet'
  • /*:然后选择所有孩子
  • [ ... ]:将方括号读为“where”
    • @includeInBook = 'true':属性“includeInBook”的内容等于“true”

答案 3 :(得分:0)

您应该考虑为此XML创建数据结构并使用“序列化”。这将是一种更清晰的方式来与此数据模型进行交互。需要考虑的事情......

相关问题