遍历 XML 文件中的所有节点 [英] Iterating through all nodes in XML file

查看:36
本文介绍了遍历 XML 文件中的所有节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to iterate through all nodes in an XML file and print their names. What is the best way to do this? I am using .NET 2.0.

推荐答案

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

I think the fastest and simplest way would be to use an XmlReader, this will not require any recursion and minimal memory foot print.

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

Here is a simple example, for compactness I just used a simple string of course you can use a stream from a file etc.

  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 文档中所有元素的列表.

A list of all the elements in the XML document.

这篇关于遍历 XML 文件中的所有节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆