.Net下XML文档的读写操作.docxVIP

  • 2
  • 0
  • 约5.12千字
  • 约 12页
  • 2016-08-24 发布于河南
  • 举报
.Net下XML文档的读写操作

一 .Net框架中与XML有关的命名空间System.Xml包含了一些和XML文档的读写操作相关的类,它们分别是:XmlReader、XmlTextReader、XmlValidatingReader、XmlNodeReader、XmlWriter、XmlTextWriter 以及 XmlNode(它的子类包括:XmlDocument、XmlDataDocument、XmlDocumentFragment)等类。System.Xml.Schema包含了和XML模式相关的类,这些类包括XmlSchema、XmlSchemaAll、XmlSchemaXPath以及XmlSchemaType等类。 System.Xml.Serialization包含了和XML文档的序列化和反序列化操作相关的类。序列化:将XML格式的数据转化为流格式的数据,并能在网络中传输;反序列化:完成相反的操作,即将流格式的数据还原成XML格式的数据。 System.Xml.Xpath包含了XPathDocument、XPathExression、XPathNavigator以及XPathNodeIterator等类,这些类能完成XML文档的导航功能。(在XPathDocument类的协助下,XPathNavigator类能完成快速的XML文档导航功能,该类为程序员提供了许多Move方法以完成导航功能。)System.Xml.Xsl完成XSLT的转换功能。二 写XML文档的方法用XmlWriter类实现写操作,该类包含了写XML文档所需的方法和属性,它是XmlTextWriter类和XmlNodeWriter类的基类。写操作的有些方法是成对出现的,比如你要写入一个元素,首先调用WriteStartElement方法—写入实际内容—调用WriteEndElement方法结束。下面通过其子类 XmlTextWriter 来说明如何写XML文档。 XmlTextWriter textWriter = New XmlTextWriter(C:\\myXmFile.xml, null);在创建完对象后,我们调用WriterStartDocument方法开始写XML文档;在完成写工作后,就调用WriteEndDocument结束写过程,并调用Close方法将它关闭。在写的过程中,我们可以:调用WriteComment方法来添加说明;通过调用WriteString方法来添加一个字符串;通过调用WriteStartElement和WriteEndElement方法对来添加一个元素;通过调用WriteStartAttribute和WriteEndAttribute方法对来添加一个属性;通过调用WriteNode方法来添加整的一个节点;其它的写的方法还包括WriteProcessingInstruction和WriteDocType等等。下面的示例介绍如何具体运用这些方法来完成XML文档的写工作。using System;using System.Xml; namespace WriteXML{class Class1{static void Main( string[] args ){try{// 创建XmlTextWriter类的实例对象XmlTextWriter textWriter = new XmlTextWriter(C:\\w3sky.xml, null);textWriter.Formatting = Formatting.Indented;// 开始写过程,调用WriteStartDocument方法textWriter.WriteStartDocument(); // 写入说明textWriter.WriteComment(First Comment XmlTextWriter Sample Example);textWriter.WriteComment(w3sky.xml in root dir); //创建一个节点textWriter.WriteStartElement(Administrator);textWriter.WriteElementString(Name, formble);textWriter.WriteElementString(site, );textWriter.WriteEndElement();// 写文档结束,调用WriteEndDocument方法textWriter.WriteEndDocument();// 关闭textWritertextWriter.Close();}catch(System.Exception e){Console.WriteLine(e.ToString());}}}}三 读XML文档的方法用Xml

文档评论(0)

1亿VIP精品文档

相关文档