【C# XML】XmlReader和XmlWrite


C#(3):XmlReader ,XmlWriter(抽象類)

 

XmlReader 類 (System.Xml) | Microsoft Docs

XmlWriter 類 (System.Xml) | Microsoft Docs

一、概述

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

  • XmlDictionaryReader
  • XmlNodeReader
  • XmlTextReader(.net 2.0 以后不建議使用 與IO命名空間中的TextReader對象一起使用)、
  • XmlValidatingReader(net 2.0 以后不建議使用 添加了DTD和模式驗證,提供數據的有效性驗證)。
•XmlReader reader =new XmlTextReader(xmlFile); •XmlReader reader =new XmlNodeReader(xmNode);

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

  • XmlTextWriter
  • XmlQueryWriter
     
     
     

二、XmlReader

1、概述

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

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

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

2、常見用法

(1)使用靜態方法Create(),返回一個XmlReader對象。

(2)Read()方法可以進入下一個節點。XmlReader類還可以讀取強類型化的數據,它有幾個ReadValuesAs方法,如、ReadValueAsDouble、ReadValueAsBoolean等。

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

XmlReader tr = XmlReader.Create("book.xml");
while (tr.AttributeCount; i++){
     richTextBox1.AppendText(tr.GetAttribute(i)+"\r\n");
     }
   }
}

 

3、使用XmlReader類進行驗證

有時不但要知道文檔的格式是規范的,還是確定文檔是有效的。

XmlReader可以使用XmlReaderSettings,根據XSD模式驗證XML。

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

XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;
settings.IgnoreWhitespace = true;
XmlReader reader = //settings參數 為可選。
List lists = new List();
CustomerInfo cust = null;

while (reader.Read())//讀取下一個節點
{
    if (reader.NodeType == XmlNodeType.Element)
    {
        switch (reader.Name)
        {
            case "row":
                cust = new CustomerInfo();
                if (reader.HasAttributes)//因屬性不是文檔結構的一部分,要專門檢查。屬性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、讀取字節數據BinHex

下面的示例讀取一個內聯 BinHex 編碼圖像。 BinHex 數據嵌入到 元素中。 BinaryWriter 用於創建一個新的二進制數據文件。

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 = 0) 

        {
            bw.Write(buffer, 0, readBytes);
        }
        outputFile.Close();
        
  }
}

 

三 、XmlWriter

1、概述

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

實例

using System.Text;
using System.Xml;
using System.Xml.Linq;




XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UTF8Encoding(false);
settings.NewLineChars = Environment.NewLine;

settings.Indent = true;
using XmlWriter xmlWriter =  XmlWriter.Create("mytext.xml", settings);
xmlWriter.WriteStartDocument(true);
//文檔類型
xmlWriter.WriteDocType("Html", null, null, "<!ENTITY h \"hardcover\">");

xmlWriter.WriteStartElement("Html");
//命名空間
xmlWriter.WriteAttributeString("xmlns", "xsi", null, "http://www/XMLSchema-instance");
xmlWriter.WriteAttributeString("xsi", "schemaLocation", null, @"http://.xsd");
//指令
String PItext = "type=\"text/xsl\" href=\"book.xsl\"";
xmlWriter.WriteProcessingInstruction("xml-stylesheet", PItext);
//注釋
xmlWriter.WriteComment("標題頭");
//cdata
xmlWriter.WriteCData(@"<javasritpt><javasritpt>");
 


xmlWriter.WriteStartElement("Head");
xmlWriter.WriteStartElement("mate");
xmlWriter.WriteAttributeString("charset", "utf-8");
xmlWriter.WriteEndElement();

xmlWriter.WriteStartElement("Title");
xmlWriter.WriteString("springsnow - 博客園<");
xmlWriter.WriteEndElement();
xmlWriter.WriteStartElement("key", "Keyword", "http://key");
xmlWriter.WriteString("園子,園子,園子");
//應用實體
xmlWriter.WriteEntityRef("h");
xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement();


/*
輸出:
    <? xml version = "1.0" encoding = "utf-8" standalone = "yes" ?>
     < !DOCTYPE Html[
     < !ENTITY h "hardcover" >] >
     < Html
    xmlns: xsi = "http://www/XMLSchema-instance" xsi: schemaLocation = "http://.xsd" >
    
        <? xml - stylesheet type = "text/xsl" href = "book.xsl" ?>
         
             < !--標題頭-- >
         
             < ![CDATA[< javasritpt >< javasritpt >]] >
         
             < Head >
         
                 < mate charset = "utf-8" />
         
                 < Title > springsnow - 博客園 & lt;</ Title >
              
                      < key:Keyword
                           xmlns:key = "http://key" > 園子,園子,園子 & h;
        </ key:Keyword >
 
     </ Head >
 </ Html >*/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM