且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过XML文件中的所有节点迭代

更新时间:2023-11-23 23:01:04

我想最快和最简单的方法是使用的的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.