XML reader: deal with various NodeType : Node Type « XML « C# / C Sharp






XML reader: deal with various NodeType

XML reader: deal with various NodeType
 
// Reading an XML document.

using System;
using System.Windows.Forms;
using System.Xml;

public class Test{

    static void Main() {
      XmlDocument document = new XmlDocument();
      document.Load( "books.xml" );

      XmlNodeReader reader = new XmlNodeReader( document );
      
      int depth = -1;

      while ( reader.Read() )
      {
         switch ( reader.NodeType )
         {
            case XmlNodeType.Element:
               depth++;
               TabOutput( depth );
               Console.WriteLine("<" + reader.Name + ">" + "\r\n");

               if ( reader.IsEmptyElement )
                  depth--;

               break;

            case XmlNodeType.Comment:
               TabOutput( depth );
               Console.WriteLine("<!--" + reader.Value + "-->\r\n");
               break;

            case XmlNodeType.Text:
               TabOutput( depth );
               Console.WriteLine("\t" + reader.Value + "\r\n");
               break;

            case XmlNodeType.XmlDeclaration:
               TabOutput( depth );
               Console.WriteLine("<?" + reader.Name + " " + reader.Value + " ?>\r\n");
               break;
            
            case XmlNodeType.EndElement:     
               TabOutput( depth );
               Console.WriteLine("</" + reader.Name + ">\r\n");
               depth--;    
               break;  
         }
      }
   } 

   static void TabOutput( int number )
   {
      for ( int i = 0; i < number; i++ )
         Console.Write("\t");
   }

}

           
         
  








Related examples in the same category

1.XmlNodeType Text
2.Read XML data from xml file: Node type, name
3.XML write: element, attribute, cddata, namespace and entity reference
4.Get boolean value from Xml
5.Get int value from Xml