迭代XML文件中的所有节点

时间:2010-05-26 17:25:22

标签: c# xml

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

5 个答案:

答案 0 :(得分:43)

您可以使用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
}

答案 1 :(得分:35)

我认为最快最简单的方法是使用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文档中所有元素的列表。

答案 2 :(得分:16)

这是我自己为自己写的:

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 :(得分:5)

迭代所有元素

XDocument xdoc = XDocument.Load("input.xml");
foreach (XElement element in xdoc.Descendants())
{
    Console.WriteLine(element.Name);
}

答案 4 :(得分:2)

相关问题