技术开发 频道

详解.NET中的XmlReader与XmlWriter

  检索属性数据

  AttributeCountry属性确定属性个数。GetAttribute()方法按照名称或索引来获取属性,如果要一次迭代一个属性就可以使用MoveToFirstAttribute()和MoveToNextAttribute()方法。

  如下代码:

richTextBox1.Clear();XmlReader tr = XmlReader.Create("book.xml");while (tr.Read()){if (tr.NodeType == XmlNodeType.Element){for (int i = 0; i < tr.AttributeCount; i++){richTextBox1.AppendText(tr.GetAttribute(i)+"\r\n");}}}

  使用XmlReader类进行验证

  有时不但要知道文档的格式是规范的,还是确定文档是有效的。

  XmlReader可以使用XmlReaderSettings,根据XSD模式验证XML。XSD模式添加到XMLSchemaSet中,通过Schema属性可以访问XMLSchemaSet。XsdValidate属性还必须设置为ture,这个属性默认为flase.

  XmlWriter类可以把Xml写入一个流、文件、StringBuilder、TextWriter或另一个XmlWriter对象中。与XmlReader一样,XmlWriter类以只向前、未缓存的方式 进行写入。

  使用XmlWirterSettings对旬进行是否缩进文本、缩进量等配置。

  如下代码:

XmlWriterSettings settings = new XmlWriterSettings();settings.Indent = true; //是否缩进settings.NewLineOnAttributes = true;  //把每个属性写在一行,这样做可以更容易读取XMLXmlWriter writer = XmlWriter.Create("booknew.xml",settings);writer.WriteStartDocument();writer.WriteStartElement("book");writer.WriteAttributeString("genre","Mystery");writer.WriteAttributeString("publicationdate","2001");writer.WriteAttributeString("ISBN","123456489");writer.WriteElementString("title","Case of the Money");writer.WriteStartElement("author");writer.WriteElementString("name","Cookie Monster");writer.WriteEndElement();writer.WriteElementString("price","9.99");       writer.WriteEndDocument();writer.Flush();writer.Close();

  1.使用XmlWriterSettings实例对象进行生成的XML的设置。

  2.使用Create(),返回一个XmlWriter对象,其中Create(),第一个参数为Xml的名字,第二个参数为XmlWriterSettings实例对象。

  3.使用WriterStartDocument()中文档声明,开始写入数据,以WriteEndDocument()结束。注间控制元素的嵌套,注注意WriterStartElement()和WriterEndElement()的调用与位置。

  4.还有一些专用的写入方法。WriteCData()可以输出一个CData部分(),WriterComment()以正确的XML格式写入注释。WriteChae()写入字符缓冲区的内容。

0
相关文章