XDocument - 遍历 XML 个元素

XDocument - Iterating Over XML Elements

举个例子 XML 文件是这样的:

<libraries>

  <library name="some library">
    <book name="my book"/>
    <book name="your book"/>
  </library>

  <library name="another library">
    <book name="his book"/>
    <book name="her book"/>
  </library>

</libraries>

如何遍历每个库并只获取其子项?例如。如果我在第一个图书馆元素中并且我去检索它的所有 descendants/children,它只会 return 里面有两本书。

我已经尝试迭代并使用 XElement.Elements("book")、XElement.Elements()、XElement.Descendants() 等,但所有 return每个元素都是一本书(因此它也会从第二个图书馆中提取元素)。大多数情况下,我认为我只是在努力理解 XDocument 如何跟踪其元素以及什么被认为是 descendant/child.

如果可能的话,如果有人可以解释如何使用 XDocument 对任何级别的元素完成此操作,我们将不胜感激(例如,如果每本书都有子元素,以及这些元素是否有子元素,等等) ).

纯粹,

问题是您正在使用 "book" 提取所有元素。

如果您只想获取依赖于父元素的项目,则必须提供适当的条件。

 var v = from n in doc.Descendants("library")
                where n.Attribute("name").Value == "some library"
                select n.DescendantNodes();

现在,这将为您提供名称为 "some library" 的元素。

您可以通过以下方式遍历库的所有后代来迭代 XML。

  XDocument doc=XDocument.Load(XmlPath);
  foreach (var item in doc.Descendants("library"))
  IEnumerable<XNode> nodes = item.DescendantNodes();//Here you got book nodes within a library