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