遍历XML文件中的所有节点

41

我想遍历XML文件中的所有节点并打印它们的名称。这样做最好的方法是什么?我正在使用.NET 2.0。

5个回答

61
你可以使用XmlDocument。此外,一些XPath可能会有用。
一个简单的例子。
XmlDocument doc = new XmlDocument();
doc.Load("sample.xml");
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("some_node"); // You can also use XPath here
foreach (XmlNode node in nodes)
{
   // use node variable here for your beeds
}

3
相较于使用XmlReader,这种方法将起始/结束元素和内容视为一个整体进行处理,因此更受青睐。 - Savage
不确定为什么foreach (XmlNode node in nodes) 只循环遍历一个顶级节点,例如("some_node"),而没有到达其下面的嵌套子节点等...在(XmlNodeList nodes)中。你能帮忙吗? - Dung

44

我认为最快、最简单的方法是使用一个XmlReader,这不需要任何递归和最小的内存占用。

以下是一个简单的例子,为了紧凑起见,我只是使用了一个简单的字符串,当然你也可以使用来自文件的流等等。

  string xml = @"
    <parent>
      <child>
        <nested />
      </child>
      <child>
        <other>
        </other>
      </child>
    </parent>
    ";

  XmlReader rdr = XmlReader.Create(new System.IO.StringReader(xml));
  while (rdr.Read())
  {
    if (rdr.NodeType == XmlNodeType.Element)
    {
      Console.WriteLine(rdr.LocalName);
    }
  }
以上代码的结果将会是:
parent
child
nested
child
other

XML文档中的所有元素列表。


21

这是我为自己快速写的:

public static class XmlDocumentExtensions
{
    public static void IterateThroughAllNodes(
        this XmlDocument doc, 
        Action<XmlNode> elementVisitor)
    {
        if (doc != null && elementVisitor != null)
        {
            foreach (XmlNode node in doc.ChildNodes)
            {
                doIterateNode(node, elementVisitor);
            }
        }
    }

    private static void doIterateNode(
        XmlNode node, 
        Action<XmlNode> elementVisitor)
    {
        elementVisitor(node);

        foreach (XmlNode childNode in node.ChildNodes)
        {
            doIterateNode(childNode, elementVisitor);
        }
    }
}

为了使用它,我使用了类似以下的方法:

var doc = new XmlDocument();
doc.Load(somePath);

doc.IterateThroughAllNodes(
    delegate(XmlNode node)
    {
        // ...Do something with the node...
    });

也许它能帮助某些人。


3
太好了!我通过逐步阅读这段代码学到了很多,感谢分享。 - reggaeguitar
2
通用方法。+1 我更喜欢这个。 - Silver

14
遍历所有元素。
XDocument xdoc = XDocument.Load("input.xml");
foreach (XElement element in xdoc.Descendants())
{
    Console.WriteLine(element.Name);
}

1
建议使用XDocument而不是XmlDocument。参见:https://dev59.com/Z3I_5IYBdhLWcg3wEOvq(甚至比这里的问题还要老)。 - Martin Schneider

4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接