Iterating through all nodes in XML file

后端 未结 5 1989
逝去的感伤
逝去的感伤 2020-11-27 05:16

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.

5条回答
  •  自闭症患者
    2020-11-27 05:58

    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 = @"
        
          
            
          
          
            
            
          
        
        ";
    
      XmlReader rdr = XmlReader.Create(new System.IO.StringReader(xml));
      while (rdr.Read())
      {
        if (rdr.NodeType == XmlNodeType.Element)
        {
          Console.WriteLine(rdr.LocalName);
        }
      }
    

    The result of the above will be

    parent
    child
    nested
    child
    other
    

    A list of all the elements in the XML document.

提交回复
热议问题