专注于互联网--专注于架构

最新标签
网站地图
文章索引
Rss订阅

首页 »XML教程 » netframework2.0:在.NET Framework中轻松处理XML数据(5-1) »正文

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

来源: 发布时间:星期四, 2009年2月12日 浏览:97次 评论:0


设计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中选中节点所有有效属性然后把属性当作个单独拷贝到当前输出流中同样WriteNode思路方法用类似思路方法处理除属性节点外其它类型节点图十所示代码片断演示了如何用上述两个思路方法创建个源XML文档拷贝,有选择修改某些节点XML树从树根开始被访问但只输出了除属性节点类型以外其它类型节点你可以把Reader和Writer整合在个新类中设计个新接口使它能读写流及访问属性和节点

Figure 10 Using the WriteNode Method

XmlTextReader reader = XmlTextReader(inputFile);

XmlTextWriter writer = XmlTextWriter(outputFile);



// 配置 reader 和 writer

writer.Formatting = Formatting.Indented;

reader.MoveToContent;



// Write根节点

writer.WriteStartElement(reader.LocalName);



// Read and output every other node

i=0;

while(reader.Read)

{

(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 ernal reader\'s Read method.

WriteAttributes
Specialized version of the writer\'s WriteAttributes method, writes out all the attributes for the given node, taking o 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 ernal writer to output the document and add a default comment text and the standard XML prolog.


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


0

相关文章

读者评论

发表评论

  • 昵称:
  • 内容: