XmlTextReader类中有一个很重要的属性-NodeType,通过该属性,我们可以知道其节点的节点类型。而枚举类型XmlNodeType中包含了诸如Attribute、CDATA、Element、Comment、Document、DocumentType、Entity、ProcessInstruction以及WhiteSpace等的XML项的类型。通过与XmlNodeType中的元素的比较,我们可以获取相应节点的节点类型并对其完成相关的操作。下面我就给出一个实例,该实例读取每个节点的NodeType,并根据其节点类型显示其中的内容,同时程序还记录了XML文件中每种节点类型的数目。
using System; using System.Xml; namespace ReadXML { class Class2 { static void Main( string[] args ) { int ws = 0; int pi = 0; int dc = 0; int cc = 0; int ac = 0; int et = 0; int el = 0; int xd = 0; XmlTextReader textReader = new XmlTextReader("C:\\books.xml"); while (textReader.Read()) { XmlNodeType nType = textReader.NodeType; // 节点类型为XmlDeclaration if (nType == XmlNodeType.XmlDeclaration) { Console.WriteLine("Declaration:" + textReader.Name.ToString()); xd = xd + 1; } // 节点类型为Comment if( nType == XmlNodeType.Comment) { Console.WriteLine("Comment:" + textReader.Name.ToString()); cc = cc + 1; } // 节点类型为Attribute if( nType == XmlNodeType.Attribute) { Console.WriteLine("Attribute:" + textReader.Name.ToString()); ac = ac + 1; } // 节点类型为Element if ( nType == XmlNodeType.Element) { Console.WriteLine("Element:" + textReader.Name.ToString()); el = el + 1; } // 节点类型为Entity if ( nType == XmlNodeType.Entity ) { Console.WriteLine("Entity:" + textReader.Name.ToString()); et = et + 1; } // 节点类型为Process Instruction if( nType == XmlNodeType. ProcessInstruction ) { Console.WriteLine("Process Instruction:" + textReader.Name.ToString()); pi = pi + 1; } // 节点类型为DocumentType if( nType == XmlNodeType.DocumentType) { Console.WriteLine("DocumentType:" + textReader.Name.ToString()); dc = dc + 1; } // 节点类型为Whitespace if ( nType == XmlNodeType.Whitespace ) { Console.WriteLine("WhiteSpace:" + textReader.Name.ToString()); ws = ws + 1; } } // 在控制台中显示每种类型的数目 Console.WriteLine("Total Comments:" + cc.ToString()); Console.WriteLine("Total Attributes:" + ac.ToString()); Console.WriteLine("Total Elements:" + el.ToString()); Console.WriteLine("Total Entity:" + et.ToString()); Console.WriteLine("Total Process Instructions:" + pi.ToString()); Console.WriteLine("Total Declaration:" + xd.ToString()); Console.WriteLine("Total DocumentType:" + dc.ToString()); Console.WriteLine("Total WhiteSpaces:" + ws.ToString()); } } }
|
以上,我向大家介绍了如何运用XmlTextReader类的对象来读取XML文档,并根据节点的NodeType属性来取得其节点类型信息。同时XmlReader这个基类还有XmlNodeReader和XmlValidatingReader等派生类,它们分别是用来读取XML文档的节点和模式的。限于篇幅,这里就不介绍了,读者可以参考有关资料。
四、写XML文档的方法
XmlWriter类包含了写XML文档所需的方法和属性,它是XmlTextWriter类和XmlNodeWriter类的基类。该类包含了WriteNode、WriteString、WriteAttributes、WriteStartElement以及WriteEndElement等一系列写XML文档的方法,其中有些方法是成对出现的。比如你要写入一个元素,你首先得调用WriteStartElement方法,接着写入实际内容,最后是调用WriteEndElement方法以表示结束。该类还包含了WriteState、XmlLang和XmlSpace等属性,其中WriteState属性表明了写的状态。因为XmlWriter类包含了很多写XML文档的方法,所以这里只是介绍最主要的几种。下面我们通过其子类XmlTextWriter类来说明如何写XML文档。
首先,我们要创建一个XmlTextWriter类的实例对象。该类的构造函数XmlTextWriter有三种重载形式,其参数分别为一个字符串、一个流对象和一个TextWriter对象。这里我们运用字符串的参数形式,该字符串就指明了所要创建的XML文件的位置,方法如下:
XmlTextWriter textWriter = New XmlTextWriter("C:\\myXmFile.xml", null); |