Mega Code Archive

 
Categories / C# Tutorial / XML
 

Read XML document by node type

using System; using System.Xml; class MainClass {     static void Main(string[] args)     {         int DecCounter=0, PICounter=0, DocCounter=0, CommentCounter=0, ElementCounter=0, AttributeCounter=0, TextCounter=0, WhitespaceCounter=0;         XmlTextReader reader = new XmlTextReader(@"C:\books.xml");         while (reader.Read())         {             XmlNodeType type = reader.NodeType;              switch (type) {                 case XmlNodeType.XmlDeclaration:                     DecCounter++;                     break;                 case XmlNodeType.ProcessingInstruction:                     PICounter++;                     break;                 case XmlNodeType.DocumentType:                     DocCounter++;                     break;                 case XmlNodeType.Comment:                     CommentCounter++;                     break;                 case XmlNodeType.Element:                     ElementCounter++;                     if (reader.HasAttributes)                         AttributeCounter += reader.AttributeCount;                     break;                 case XmlNodeType.Text:                     TextCounter++;                     break;                 case XmlNodeType.Whitespace:                     WhitespaceCounter++;                     break;             }                        }         Console.WriteLine("White Spaces:" +WhitespaceCounter.ToString());         Console.WriteLine("Process Instructions:" +PICounter.ToString());         Console.WriteLine("Declaration:" +DecCounter.ToString());         Console.WriteLine("White Spaces:" +DocCounter.ToString());         Console.WriteLine("Comments:" +CommentCounter.ToString());         Console.WriteLine("Attributes:" +AttributeCounter.ToString());     } }