欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#使?XmlReader和XmlWriter操作XML?件

 更新時(shí)間:2022年06月06日 08:42:22   作者:springsnow  
這篇文章介紹了C#使?XmlReader和XmlWriter操作XML?件的方法,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

一、概述

1、XMLReader為抽象類,其派生類有:

  • XmlDictionaryReader
  • XmlNodeReader
  • XmlTextReader(與IO命名空間中的TextReader對(duì)象一起使用)、
  • XmlValidatingReader(添加了DTD和模式驗(yàn)證,提供數(shù)據(jù)的有效性驗(yàn)證)。
?XmlReader reader =new XmlTextReader(xmlFile);
?XmlReader reader =new XmlNodeReader(xmNode);

2、XMLWriter為抽象類,其派生類有

  • XmlTextWriter
  • XmlQueryWriter

二、XmlReader

1、概述

XmlDocument和XElement在讀取Xml時(shí)要將整個(gè)Xml文檔放到內(nèi)存中去操作,這樣做操作簡單,但是很費(fèi)內(nèi)存。而在有些場(chǎng)景下我們必須考慮盡可能節(jié)省內(nèi)存,這時(shí)候就該XmlReaderXmlWriter出場(chǎng)了。

XmlReader非常類似于SAX。它們最大的區(qū)別是SAX是一種推模型(所有XML數(shù)據(jù)都必須由應(yīng)用程序處理,無論是否需要這些數(shù)據(jù)),XmlReader是一種拉模型(如果不需要所有的數(shù)據(jù),就不需要處理它們)。

XmlReader讀取Xml需要通過Read()實(shí)例方法,不斷讀取Xml文檔中的聲明,節(jié)點(diǎn)開始,節(jié)點(diǎn)內(nèi)容,節(jié)點(diǎn)結(jié)束,以及空白等等,直到文檔結(jié)束Read()方法返回false。

2、常見用法

(1)使用靜態(tài)方法Create(),返回一個(gè)XmlReader對(duì)象。

(2)Read()方法可以進(jìn)入下一個(gè)節(jié)點(diǎn)。XmlReader類還可以讀取強(qiáng)類型化的數(shù)據(jù),它有幾個(gè)ReadValuesAs方法,如、ReadValueAsDouble、ReadValueAsBoolean等。

(3)獲取屬性數(shù)據(jù):AttributeCountry屬性確定屬性個(gè)數(shù)。GetAttribute()方法按照名稱或索引來獲取屬性,如果要一次迭代一個(gè)屬性就可以使用MoveToFirstAttribute()和MoveToNextAttribute()方法。

XmlReader tr = XmlReader.Create("book.xml");
while (tr.Read()){
if (tr.NodeType == XmlNodeType.Element){
   for (int i = 0; i < tr.AttributeCount; i++){
     richTextBox1.AppendText(tr.GetAttribute(i)+"\r\n");
     }
   }
}

3、使用XmlReader類進(jìn)行驗(yàn)證

有時(shí)不但要知道文檔的格式是規(guī)范的,還是確定文檔是有效的。

XmlReader可以使用XmlReaderSettings,根據(jù)XSD模式驗(yàn)證XML。

XSD模式添加到XMLSchemaSet中,通過Schema屬性可以訪問XMLSchemaSet。XsdValidate屬性還必須設(shè)置為ture,這個(gè)屬性默認(rèn)為flase.

XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;
settings.IgnoreWhitespace = true;
XmlReader reader = XmlReader.Create("Customer2.xml", settings);//settings參數(shù) 為可選。
List lists = new List();
CustomerInfo cust = null;

while (reader.Read())//讀取下一個(gè)節(jié)點(diǎn)
{
    if (reader.NodeType == XmlNodeType.Element)
    {
        switch (reader.Name)
        {
            case "row":
                cust = new CustomerInfo();
                if (reader.HasAttributes)//因?qū)傩圆皇俏臋n結(jié)構(gòu)的一部分,要專門檢查。屬性HasValue是否有值;IsEmptyElement:是否為空元素
                {
                    cust.AppId = reader.GetAttribute("AppID");
                    cust.Version = reader.GetAttribute("Version");
                }
                break;

            case "CustomerID":
                cust.CustomerID = reader.ReadString();
                break;

            case "CompanyName":
                cust.CompanyName = reader.ReadString();
                break;
            default:
                break;

        }
    }
}

4、讀取字節(jié)數(shù)據(jù)BinHex

下面的示例讀取一個(gè)內(nèi)聯(lián) BinHex 編碼圖像。 BinHex 數(shù)據(jù)嵌入到 元素中。 BinaryWriter 用于創(chuàng)建一個(gè)新的二進(jìn)制數(shù)據(jù)文件。

public static void BinHexDecodeImageFile() {

  byte[] buffer = new byte[1000];
  int readBytes = 0;

  using (XmlReader reader = XmlReader.Create("output.xml")) {
                       
        FileStream outputFile = new FileStream(@"C:\artFiles\data\newImage.jpg", FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write);
        // Read to the image element.
        reader.ReadToFollowing("image");
        // Read the BinHex data.
        Console.WriteLine("\r\nReading BinHex...");
        BinaryWriter bw = new BinaryWriter(outputFile);
        while ((readBytes = reader.ReadElementContentAsBinHex(buffer, 0, 50))>0) 
        {
            bw.Write(buffer, 0, readBytes);
        }
        outputFile.Close();
        
  }
}

三 、XmlWriter

1、概述

與XmlReader一樣,XmlWriter類以只向前、未緩存的方式 進(jìn)行寫入。

2、常見用法

1、寫Xml文檔聲明

WriteStartDocument方法可以接受一個(gè)bool參數(shù)(表示standalone,是否為獨(dú)立文檔)或者不指定參數(shù)standalone保持默認(rèn)值

xmlWriter.WriteStartDocument(false|true);

注意在使用WriteStartDocument方法后最好調(diào)用xmlWrite.WriteEndDocument()方法來關(guān)閉所有可能未關(guān)閉標(biāo)簽

2、寫xml節(jié)點(diǎn)以及屬性

//寫節(jié)點(diǎn)
xmlWriter.WriteStartElement("cat");

//給節(jié)點(diǎn)添加屬性
xmlWriter.WriteAttributeString("color", "white");

//給節(jié)點(diǎn)內(nèi)部添加文本
xmlWriter.WriteString("I'm a cat");
xmlWriter.WriteEndElement(); 

//或者通過WriteElementString(string,string)方法寫xml節(jié)點(diǎn)同時(shí)寫下節(jié)點(diǎn)值,如下
xmlWriter.WriteElementString("pig", "pig is great");

3、寫CData

xmlWriter.WriteCData("dog is dog");

4、如添加注釋

xmlWriter.WriteComment("*** ");

5、如何設(shè)置XmlWriter的輸出格式,解決輸出UTF-16問題

設(shè)置xml輸出格式,需要通過XmlWriterSettings類,如下代碼

XmlWriterSettings settings = new XmlWriterSettings();

//要求縮進(jìn)
settings.Indent = true;

//注意如果不設(shè)置encoding默認(rèn)將輸出utf-16
 //注意這兒不能直接用Encoding.UTF8如果用Encoding.UTF8將在輸出文本的最前面添加4個(gè)字節(jié)的非xml內(nèi)容
settings.Encoding = new UTF8Encoding(false);

 //設(shè)置換行符
settings.NewLineChars = Environment.NewLine;

6、寫入其他對(duì)象中

XmlWriter類可以把Xml寫入一個(gè)流、文件、StringBuilder、TextWriter或另一個(gè)XmlWriter對(duì)象中。

7、命名空間的支持

XmlTextWriter w = new XmlTextWriter(Console.Out);
w.WriteStartElement("x","root","urn:1");
w.WriteStartElement("y","item","urn:1");
w.WriteAttributeString("abc","urn:1","xyz");
w.WriteEndElement();
w.WriteEndElement();
w.Close();

3、XmlWriter完整的代碼示例

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = "\t";
settings.NewLineOnAttributes = false;
settings.ConformanceLevel = ConformanceLevel.Auto;
settings.OmitXmlDeclaration = false;

//注意如果不設(shè)置encoding默認(rèn)將輸出utf-16
//注意這兒不能直接用Encoding.UTF8如果用Encoding.UTF8將在輸出文本的最前面添加4個(gè)字節(jié)的非xml內(nèi)容
settings.Encoding = new UTF8Encoding(false);

//設(shè)置換行符
settings.NewLineChars = Environment.NewLine;

XmlWriter writer = XmlWriter.Create("CustomerNewElementArribute.xml", settings);//settings參數(shù) 為可選。
//使用xmlwriter寫入StringBuiler和Stream:
//StringBuilder builder = new StringBuilder();
//XmlWriter writer = XmlWriter.Create(builder, settings);
//MemoryStream stream = new MemoryStream();
//XmlWriter writer = XmlWriter.Create(stream, settings);
writer.WriteStartDocument();//寫Xml聲明:可選參數(shù)表示standalone,是否為獨(dú)立文檔
writer.WriteComment("XXX"); //寫注釋
writer.WriteStartElement("Table");//寫復(fù)雜元素(元素含有子元素)
for (int i = 1; i < 10; i++)
{
    writer.WriteStartElement("row");
    writer.WriteAttributeString("Version", "2.0");
    writer.WriteAttributeString("AppID", "111");
    writer.WriteElementString("CustomerID", "cmz" + i.ToString());//寫簡單元素
    writer.WriteElementString("CompanyName", "程沐喆" + i.ToString());
    writer.WriteEndElement();
}

writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
writer.Close();

4、寫入字節(jié)數(shù)據(jù)BinHex

//用 WriteBinHex 方法編寫 BinHex 數(shù)據(jù)。 BinHex 數(shù)據(jù)嵌入在  元素。
int bufferSize = 1000;
byte[] buffer = new byte[bufferSize];
int readBytes = 0;

using (XmlWriter writer = XmlWriter.Create("output.xml"))
{
    FileStream inputFile = new FileStream(@"C:\sunset.jpg", FileMode.OpenOrCreate,FileAccess.Read, FileShare.Read);
    writer.WriteStartDocument();
    writer.WriteStartElement("image");
    BinaryReader br = new BinaryReader(inputFile);
    Console.WriteLine("\r\nWriting BinHex data...");

    do
    {
        readBytes = br.Read(buffer, 0, bufferSize);
        writer.WriteBinHex(buffer, 0, readBytes);
    } while (bufferSize <= readBytes);
    br.Close();

    writer.WriteEndElement();//
    writer.WriteEndDocument();
}

到此這篇關(guān)于C#使?XmlReader和XmlWriter操作XML?件的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論