AutoCAD 3DMAX C语言 Pro/E UG JAVA编程 PHP编程 Maya动画 Matlab应用 Android
Photoshop Word Excel flash VB编程 VC编程 Coreldraw SolidWorks A Designer Unity3D
 首页 > XML

在.NET Framework中轻松处理XML数据(五)

51自学网 http://www.51zixue.net

设计XmlReadWriter类

如前面所说,XML reader和Writer是各自独立工作的:reader只读,writer只写。假设你的应用程序要管理冗长的XML文档,且该文档有不确定的数据。Reader提供了一个很好的方法去读该文档的内容。另一方面,Writer是一个非常有用的用于创建XML文档片断工具,但是如果你想要它即能读,又能写,那么你就要用XMLDOM了。如果实际的XML文档非常庞大,又会出现了一个问题,什么问题呢?是不是把这个XML文档全部加载到内存中,然后进行读和写呢?让我们先看一下怎么样建立一个混合的流分析器用于分析大型的XMLDOM。

像一般的只读操作一样,用普通的XML reader去顺序的访问节点。不同的是,在读的同时你可以用XML writer改变属性值以及节点的内容。你用reader去读源文件中的每个节点,后台的writer创建该节点的一个拷贝。在这个拷贝中,你可以增加一些新的节点,忽略或者编辑其它的一些节点,还可以编辑属性的值。当你完成修改后,你就用新的文档替换旧的文档。

一个简单有效的办法是从只读流中拷贝节点对象到write流中,这种方法可以用XmlTextWriter类中的两个方法:WriteAttributes方法和WriteNode方法。 WriteAttributes方法读取当前reader中选中的节点的所有有效的属性,然后把属性当作一个单独的string拷贝到当前的输出流中。同样的,WriteNode方法用类似的方法处理除属性节点外的其它类型的节点。图十所示的代码片断演示了怎么用上述的两个方法创建一个源XML文档的拷贝,有选择的修改某些节点。XML树从树根开始被访问,但只输出了除属性节点类型以外的其它类型的节点。你可以把Reader和Writer整合在一个新的类中,设计一个新的接口,使它能读写流及访问属性和节点。

Figure 10 Using the WriteNode Method

XmlTextReader reader = new XmlTextReader(inputFile);

XmlTextWriter writer = new XmlTextWriter(outputFile);



// 配置 reader 和 writer

writer.Formatting = Formatting.Indented;

reader.MoveToContent();



// Write根节点

writer.WriteStartElement(reader.LocalName);



// Read and output every other node

int i=0;

while(reader.Read())

{

if (i % 2)

writer.WriteNode(reader, false);

i++;

}



// Close the root

writer.WriteEndElement();



// Close reader and writer

writer.Close();

reader.Close();

我的XmlTextReadWriter类并没有从XmlReader或者XmlWriter类中继承。取而代之的是另外两个类,一个是基于只读流(stream)的操作类,另一个是基于只写流的操作类。XmlTextReadWriter类的方法用Reader对象读数据,写入到Writer对象。为了适应不同的需求,内部的Reader和Writer 对象分别通过只读的Reader和Writer属性公开。图十一列出了该类的一些方法:

Figure 11 XmlTextReadWriter Class Methods

Method
Description

AddAttributeChange
Caches all the information needed to perform a change on a node attribute. All the changes cached through this method are processed during a successive call to WriteAttributes.

Read
Simple wrapper around the internal reader's Read method.

WriteAttributes
Specialized version of the writer's WriteAttributes method, writes out all the attributes for the given node, taking into account all the changes cached through the AddAttributeChange method.

WriteEndDocument
Terminates the current document in the writer and closes both the reader and the writer.

WriteStartDocument
Prepares the internal writer to output the document and add a default comment text and the standard XML prolog.


这个新类有一个Read方法,它是对Reader的read方法的一个简单的封装。另外,它提供了WriterStartDocument和WriteEndDocument方法。它们分别初始化/释放(finalize)了内部Reader和writer对象,还处理所有I/O操作。在循环读节点的同时,我们就可以直接的修改节点。出于性能的原因,要修改属性必须先用AddAttributeChange方法声明。对一个节点的属性所作的所有修改都会存放在一个临时的表中,最后,通过调用WriteAttribute方法提交修改,清除临时表。

<

 

 

 
上一篇:在.NET&nbsp;Framework中轻松处理XML数据(三)  下一篇:XML在.net平台下的自定义控件的应用(1)