频道栏目
首页 > 资讯 > XML教程 > 正文

在.NET Framework中轻松处理XML数据(5-1)

16-01-06        来源:[db:作者]  
收藏   我要投稿
??设计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方法提交修正,清除临时表。


相关TAG标签
上一篇:在.NET Framework中轻松处理XML数据(4-3)
下一篇:在.NET Framework中轻松处理XML数据(4-4)
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站