通过XML文件中的所有节点迭代 [英] Iterating through all nodes in XML file

查看:152
本文介绍了通过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天全站免登陆