C# 遍历XML文件中的所有节点

C# 遍历XML文件中的所有节点,c#,xml,C#,Xml,我希望遍历XML文件中的所有节点并打印它们的名称。 最好的方法是什么?我正在使用.NET 2.0。您可以使用。此外,一些XPath也很有用 只是一个简单的例子 XmlDocument doc = new XmlDocument(); doc.Load("sample.xml"); XmlElement root = doc.DocumentElement; XmlNodeList nodes = root.SelectNodes("some_node"); // You can also use

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

您可以使用。此外,一些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
}

通过
XmlDocument

以下是一个例子-


这里是另一个递归示例-

我认为最快和最简单的方法是使用,这将不需要任何递归和最小的内存足迹

这里有一个简单的例子,为了简洁,我只使用了一个简单的字符串,当然你可以使用来自文件的流等等

  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);
    }
  }

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

这是我很快为自己编写的内容:

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);
        }
    }
}

也许这对其他人有帮助。

遍历所有元素

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

这太棒了!通过这段代码,我学到了很多,谢谢分享。通用方法+1我更喜欢这个。更喜欢这个,因为它将开始/结束元素和内容视为单个项,而不是使用XmlReadernot确定为什么foreach(节点中的XmlNode节点)只循环通过1个顶部节点,例如(“some_节点”),而不到达它下面的嵌套子节点等等。。。在(XmlNodeList节点)中。你能帮忙吗?比起
XmlDocument
,你更喜欢使用这个。见:(比这里的问题还要老)
var doc = new XmlDocument();
doc.Load(somePath);

doc.IterateThroughAllNodes(
    delegate(XmlNode node)
    {
        // ...Do something with the node...
    });
XDocument xdoc = XDocument.Load("input.xml");
foreach (XElement element in xdoc.Descendants())
{
    Console.WriteLine(element.Name);
}