DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> XML學習教程 >> XML基礎 >> 在.NET Framework中輕松處理XML數據(五)
在.NET Framework中輕松處理XML數據(五)
編輯:XML基礎     
設計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方法提交修改,清除臨時表。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved