获取特定类型的所有XML ChildNodes

时间:2021-01-04 16:06:11

Given the following code:

给出以下代码:

XmlDocument doc = new XmlDocument();
doc.Load(filename);
XmlElement root = doc.DocumentElement;

What is the most efficient way to get all the child nodes of root that are of type "item". There can be more than one element of that type. But most elements are of other types.

获取类型为“item”的root的所有子节点的最有效方法是什么。该类型可以有多个元素。但大多数元素都属于其他类型。

I know I can do this:

我知道我可以这样做:

root["item"];

But that only returns a single element. How can I do the same thing but return all elements of that type?

但这只返回一个元素。我怎么能做同样的事情但返回那种类型的所有元素?

Thanks!

1 个解决方案

#1


0  

    XmlDocument doc = new XmlDocument();
    doc.Load(filename);
    var nodes = doc.SelectNodes("/root/item");

You can test different XPaths here.

您可以在此处测试不同的XPath。

But, in my opinion, you are better off with Linq2XML.

但是,在我看来,你最好使用Linq2XML。

#1


0  

    XmlDocument doc = new XmlDocument();
    doc.Load(filename);
    var nodes = doc.SelectNodes("/root/item");

You can test different XPaths here.

您可以在此处测试不同的XPath。

But, in my opinion, you are better off with Linq2XML.

但是,在我看来,你最好使用Linq2XML。