您的位置:首页 > 其它

[导入]如何完成.Net下XML文档的读写操作

2007-12-25 11:21 387 查看
本人在.Net下学习 XML 的过程中,对如何完成 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

using System;

using System.Xml;

namespace ReadXml

<?xml version='1.0'?>

<!-- This file represents a fragment of a book store inventory database -->

<bookstore>

<book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0">

<title>The Autobiography of Benjamin Franklin</title>

<author>

<first-name>Benjamin</first-name>

<last-name>Franklin</last-name>

</author>

<price>8.99</price>

</book>

<book genre="novel" publicationdate="1967" ISBN="0-201-63361-2">

<title>The Confidence Man</title>

<author>

<first-name>Herman</first-name>

<last-name>Melville</last-name>

</author>

<price>11.99</price>

</book>

<book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6">

<title>The Gorgias</title>

<author>

<first-name>Sidas</first-name>

<last-name>Plato</last-name>

</author>

<price>9.99</price>

</book>

</bookstore>

[/b]

钢钢 2007-12-25 11:21 发表评论[小组] [博问] [闪存]
文章来源:http://www.cnblogs.com/xugang/archive/2007/12/25/1013789.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: