用 System.Xml 讀寫XML

《原文地址:http://www.cnblogs.com/surfsky/archive/2007/03/13/673625.html#673666

用 System.Xml 讀寫XML  

example
    <?xml version="1.0" encoding="utf-8"?>
    <LinkLibrary xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <Link Cat="aa" Url="aa" Desc="aa" />
      <Link Cat="bb" Url="aa" Desc="aa" />
      <Link Cat="cc" Url="aa" Desc="aa" />
      <Link Cat="aa" Url="aa" Desc="aa" />
      <Link Cat="aa" Url="aa" Desc="aa" />
      <Link Cat="aa" Url="aa" Desc="aa" />
      <Link Cat="aa" Url="aa" Desc="aa" />
      <Link Cat="aa" Url="aa" Desc="aa" />
      <Link Cat="aa" Url="aa" Desc="aa" />
      <Link Cat="aa" Url="aa" Desc="aa" />
    </LinkLibrary>


XML概念
    Root        XML根節點,只能且必須有一個(以上爲LinkLibrary)
    Element     節點元素(如Link)
    Attribute   節點屬性(如Cat, Url, Desc)
    Content     內容(非空白文本、CDATA、Element、EndElement、EntityReference 或 EndEntity)節點

System.Xml空間
    以下類適合快速流式讀寫XML文件(注:DOM適合隨機讀寫)
    XmlReader, XmlWriter,
    XmlTextReader, XmlTextWriter
    XmlValidatingReader, XmlValidatingWriter    添加了DTD和模式驗證,因此提供了數據的有效性驗證
    XmlNodeReader, XmlNodeWriter                把XmlNode作爲其源


節點類型(public enum XmlNodeType)
     XmlDeclaration        XML 聲明(例如,<?xml version='1.0'?>)。
     Attribute             屬性(例如,id='123')。
     CDATA                 CDATA 節(例如,<![CDATA[my escaped text]]>)。
     Comment               註釋(例如,<!-- my comment -->)
     Document              作爲文檔樹的根的文檔對象提供對整個 XML 文檔的訪問。
     DocumentFragment      文檔片段。
     DocumentType          由以下標記指示的文檔類型聲明(例如,<!DOCTYPE...>)。
     Element               元素(例如,<item>)。
     EndElement            末尾元素標記(例如,</item>)。
     Entity                實體聲明(例如,<!ENTITY...>)。
     EndEntity             由於調用 ResolveEntity 而使 XmlReader 到達實體替換的末尾時返回。 
     EntityReference       實體引用(例如,&num;)。
     None                  如果未調用 Read 方法,則由 XmlReader 返回。 
     Notation              文檔類型聲明中的表示法(例如,<!NOTATION...>)。
     ProcessingInstruction 處理指令(例如,<?pi test?>)。
     SignificantWhitespace 混合內容模型中標記間的空白或 xml:space="preserve" 範圍內的空白。 
     Text                  節點的文本內容。
     Whitespace            標記間的空白。 


------------------------------------------------------------------------
使用XmlTextReader快速讀取
------------------------------------------------------------------------
創建
    打開            XmlTextReader reader = new XmlTextReader("*.xml");
    關閉            reader.Close();

屬性
    常用
        HasAttributes            獲取一個值,該值指示當前節點是否有任何屬性。(從 XmlReader 繼承。)
        HasValue                 獲取一個值,該值指示當前節點是否可以具有非 String.Empty 的 Value。
        AttributeCount           獲取當前節點上的屬性數。
        Value                    獲取當前節點的文本值。
        ValueType                獲取當前節點的公共語言運行庫 (CLR) 類型。(從 XmlReader 繼承。)
        Name                     獲取當前節點的限定名。
    其它
        BaseURI                  獲取當前節點的基 URI。
        CanReadBinaryContent     獲取一個值,該值指示 XmlTextReader 是否實現二進制內容讀取方法。
        CanReadValueChunk        獲取一個值,該值指示 XmlTextReader 是否實現 ReadValueChunk 方法。
        CanResolveEntity         獲取一個值,該值指示此讀取器是否可以分析和解析實體。
        Depth                    獲取 XML 文檔中當前節點的深度。
        Encoding                 獲取文檔的編碼方式。
        EntityHandling           獲取或設置一個值,該值指定讀取器如何處理實體。
        EOF                      獲取一個值,該值指示讀取器是否定位在流的結尾。
        IsDefault                獲取一個值,該值指示當前節點是否是從 DTD 或架構中定義的默認值生成的屬性。
        IsEmptyElement           獲取一個值,該值指示當前節點是否爲空元素(例如,<MyElement/>)。
        Item                     當在派生類中被重寫時,獲取此屬性的值。(從 XmlReader 繼承。)
        LineNumber               獲取當前行號。
        LinePosition             獲取當前行位置。
        LocalName                獲取當前節點的本地名稱。
        Namespaces               獲取或設置一個值,該值指示是否進行命名空間支持。
        NamespaceURI             獲取讀取器定位在的節點的命名空間 URI(採用 W3C 命名空間規範中定義的形式)。
        NameTable                獲取與此實現關聯的 XmlNameTable。
        NodeType                 獲取當前節點的類型。
        Normalization            獲取或設置一個值,該值指示是否正常化空白和屬性值。
        Prefix                   獲取與當前節點關聯的命名空間前綴。
        ProhibitDtd              獲取或設置一個值,該值指示是否允許 DTD 處理。
        QuoteChar                獲取用於括起屬性節點值的引號字符。
        ReadState                獲取讀取器的狀態。
        SchemaInfo               獲取作爲架構驗證結果分配給當前節點的架構信息。(從 XmlReader 繼承。)
        Settings                 獲取用於創建此 XmlTextReader 實例的 XmlReaderSettings 對象。
        WhitespaceHandling       獲取或設置一個值,該值指定如何處理空白。
        XmlLang                  獲取當前 xml:lang 範圍。
        XmlResolver              設置用於解析 DTD 引用的 XmlResolver。
        XmlSpace                 獲取當前 xml:space 範圍。

方法
    定位           
        MoveToAttribute            移動到指定的屬性。 
        MoveToContent              檢查當前節點是否是內容節點, 如果此節點不是內容節點,則讀取器向前跳至下一個內容節點或文件結尾。
        MoveToElement              移動到包含當前屬性節點的元素
        MoveToFirstAttribute       移動到第一個屬性
        MoveToNextAttribute      移動到下一個屬性
        Skip                                跳過當前節點的子級。 
        IsStartElement                測試當前內容節點是否是開始標記。
 
    基本讀取           
        Read                       讀取一個節點
        ReadString                 將元素或文本節點的內容讀取爲一個字符串。


    讀取特定類型
        ReadBase64                 對 Base64 進行解碼並返回解碼的二進制字節。
        ReadBinHex                 對 BinHex 進行解碼並返回解碼後的二進制字節
        ReadChars                  將元素的文本內容讀入字符緩衝區。通過連續調用此方法,可以讀取大的嵌入文本流。
        ReadValueChunk             讀取嵌入在 XML 文檔中的大量文本流。 (從 XmlReader 繼承。)
        ReadInnerXml               將內部XML節點內容讀到一個字符串中
        ReadOuterXml               所有XML節點內容(包括自身節點)

    讀取節點
        ReadStartElement           檢查當前節點是否爲元素並將讀取器推進到下一個節點。
        ReadElementString          這是一個用於讀取簡單純文本元素的 Helper 方法。
        ReadAttributeValue         將屬性值分析爲一個或多個 Text、EntityReference 或 EndEntity 節點
        ReadEndElement             檢查當前內容節點是否爲結束標記並將讀取器推進到下一個節點。
        GetAttribute                   獲取屬性的值。 

    讀取內容並轉化
        ReadContentAs...           將內容作爲指定類型的對象讀取。 (從 XmlReader 繼承。)
        ReadElementContentAs...    讀取當前元素,並將內容作爲指定類型的對象返回。 (從 XmlReader 繼承。)

    追溯讀取
        ReadToFollowing            一直讀取,直到找到具有指定限定名的元素
        ReadToDescendant           讓 XmlReader 前進到下一個匹配的子代元素。
        ReadToNextSibling          讓 XmlReader 前進到下一個匹配的同級元素。
        GetRemainder               獲取已緩衝的 XML 剩餘部分。
        ReadSubtree                返回新的 XmlReader 實例,此實例可用於讀取當前節點及其所有子節點。

------------------------------------------------------------------------
使用XmlTextWriter快速寫入
------------------------------------------------------------------------
開閉           
    XmlTextWriter writer = new XmlTextWriter(@"c:/mywriter.xml", null);
    writer.Close();
   
起止XML文檔 (<?xml version="1.0"?>
    writer.WriteStartDocument();
    writer.EndDocument();

聲明XML格式
    writer.Formatting  = Formatting.Indented;
    writer.Indentation = 縮進字符數
    writer.IndentChar  = 縮進字符
    writer.QuoteChar   = 單引號|雙引號

輸出註釋 (<!-- comment text -->)
    writer.WriteComment("comment text");

輸出元素 (<Element>ElementVal</Element>)
    writer.WriteElementString("Element", "ElementVal");
    或者
    writer.StartElement("Element");
    writer.WriteString("ElementVal");
    writer.EndElement();

輸出元素屬性 (<Element Property="PropertyVal">ElementVal</Element>)
    writer.StartElement("Element");
    writer.WriteAttributeString("Property", "PropertyVal");
    writer.WriteString("ElementVal");
    writer.EndElement();

輸出CDATA (<!CDATA>....</CDATA>
    WriteCData("....")

輸出字符緩衝區文本
    WriteChars(char[], startPos, length)
    
  

------------------------------------------------------------------------
讀例程
------------------------------------------------------------------------
XML文件
    <!-- sample xml file -->
    <bookstore>
      <book genre='novel' ISBN='10-861003-324'>
        <title>The Handmaid's Tale</title>
        <price>19.95</price>
      </book>
      <book genre='novel' ISBN='1-861001-57-5'>
        <title>Pride And Prejudice</title>
        <price>24.95</price>
      </book>
    </bookstore>


取每個書節點上的ISBN屬性
    using (XmlReader reader = XmlReader.Create("books.xml"))
    {
        reader.ReadToFollowing("book");
        do {
           Console.WriteLine("ISBN: {0}", reader.GetAttribute("ISBN"));
        } while (reader.ReadToNextSibling("book"));
    }

跳到子節點
    using (XmlReader reader = XmlReader.Create("2books.xml"))
    {
        reader.MoveToContent();                 // bookstore
        reader.ReadToDescendant("book");        // 第一個book
        reader.Skip(); //Skip the first book.   // 第二個book
        ...
    }
   
挖到子節點
    using (XmlReader reader = XmlReader.Create("book3.xml"))
    {
        reader.Read();
        reader.ReadStartElement("book");
            reader.ReadStartElement("title");
                Console.WriteLine("The content of the title element:  {0}", reader.ReadString());
            reader.ReadEndElement();
            reader.ReadStartElement("price");
                Console.WriteLine("The content of the price element:  {0}", reader.ReadString());
            reader.ReadEndElement();
        reader.ReadEndElement();
    }

讀到指定位置  
   FileStream fs = new FileStream("..//..//..//books.xml", FileMode.Open);
   XmlTextReader tr = new XmlTextReader(fs);
   while(!tr.EOF)
   {
      // 查找類型爲XmlNodeType.Element和名稱爲title的節點
      if(tr.MoveToContent() == XmlNodeType.Element && tr.Name=="title")
      {
         listBox1.Items.Add(tr.ReadElementString());
      }
      else
      {
         tr.Read();
      }
    }

遍歷元素屬性
   string fileName = "..//..//..//books.xml";
   XmlTextReader tr = new XmlTextReader(fileName);
   while(tr.Read())
   {
      //check to see if it's a NodeType element
      if(tr.NodeType == XmlNodeType.Element) 
      {
         //if it's an element, then let's look at the attributes.
         for(int i = 0; i < tr.AttributeCount; i++) {
            listBox1.Items.Add(tr.GetAttribute(i));
      }
}

   
------------------------------------------------------------------------
寫例程
------------------------------------------------------------------------
     XmlTextWriter writer = new XmlTextWriter (filename, null);

     //Use indenting for readability.
     writer.Formatting = Formatting.Indented;

     //xml聲明(Write the XML delcaration. )
     writer.WriteStartDocument();

     //預處理指示(Write the ProcessingInstruction node.)
     String PItext="type='text/xsl' href='book.xsl'";
     writer.WriteProcessingInstruction("xml-stylesheet", PItext);

     //文檔類型(Write the DocumentType node.)
     writer.WriteDocType("book", null , null, "<!ENTITY h 'hardcover'>");
       
     //註釋(Write a Comment node.)
     writer.WriteComment("sample XML");
   
     //根元素(Write a root element.)
     writer.WriteStartElement("book");

     //屬性值(Write the genre attribute.)
     writer.WriteAttributeString("genre", "novel");
   
     //屬性值(Write the ISBN attribute.)
     writer.WriteAttributeString("ISBN", "1-8630-014");

     //Write the title.
     writer.WriteElementString("title", "The Handmaid's Tale");
             
     //Write the style element.
     writer.WriteStartElement("style");
     writer.WriteEntityRef("h");
     writer.WriteEndElement();

     //文本元素節點(Write the price.)
     writer.WriteElementString("price", "19.95");

     //[CDATA]
     writer.WriteCData("Prices 15% off!!");

     //Write the close tag for the root element.
     writer.WriteEndElement();
            
     writer.WriteEndDocument();

     //Write the XML to file and close the writer.
     writer.Flush();
     writer.Close(); 

     //Load the file into an XmlDocument to ensure well formed XML.
     XmlDocument doc = new XmlDocument();
     //Preserve white space for readability.
     doc.PreserveWhitespace = true;
     //Load the file.
     doc.Load(filename); 
   
     //Display the XML content to the console.
     Console.Write(doc.InnerXml); 


------------------------------------------------------------------------
帶驗證的讀寫
------------------------------------------------------------------------
    books.xml
        <?xml version='1.0'?>
        <!-- This file represents a fragment of a book store inventory database -->
        <bookstore xmlns="x-schema:books.xdr">
           <book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0">
              <title>The Autobiography of Benjamin Franklin</title>
              <author>
                 <first-name>Benjamin</first-name>
                 <list-name>Franklin</last-name>
              </author>
              <price>8.99</price>
           </book>
           ...
        </bookstore>
    books.xdr
        <?xml version="1.0"?>
        <Schema xmlns="urn:schemas-microsoft-com:xml-data" xmlns:dt="urn:schemas-microsoft-com:datatypes">
           <ElementType FTEL="first-name" content="textOnly"/>
           <ElementType FTEL="last-name" content="textOnly"/>
           <ElementType FTEL="name" content="textOnly"/>
           <ElementType FTEL="price" content="textOnly" dt:type="fixed.14.4"/>
           <ElementType FTEL="author" content="eltOnly" order="one">
              <group order="seq">
                 <element type="name"/>
              </group>
              <group order="seq">
                 <element type="first-name"/>
                 <element type="last-name"/>
              </group>
           </ElementType>
           <ElementType FTEL="title" content="textOnly"/>
           <AttributeType FTEL="genre" dt:type="string"/>
           <ElementType FTEL="book" content="eltOnly">
              <attribute type="genre" required="yes"/>
              <element type="title"/>
              <element type="author"/>
              <element type="price"/>
           </ElementType>
           <ElementType FTEL="bookstore" content="eltOnly">
              <element type="book"/>
           </ElementType>
        </Schema>
    cs
        using System.Xml.Schema;
        protected void button1_Click (object sender, System.EventArgs e)
        {
           //change this to match your path structure.
           string fileName = "..//..//..//booksVal.xml";
           XmlTextReader tr = new XmlTextReader(fileName);
           XmlValidatingReader trv = new XmlValidatingReader(tr);
        
           //Set validation type
           trv.ValidationType=ValidationType.XDR;
           //Add in the Validation eventhandler
           trv.ValidationEventHandler += new ValidationEventHandler(this.ValidationEvent);
        
           //Read in node at a time       
           while(trv.Read()) 
           {
              if(trv.NodeType == XmlNodeType.Text)
              listBox1.Items.Add(trv.Value);
           }
        }
        public void ValidationEvent (object sender, ValidationEventArgs args)
        {
           MessageBox.Show(args.Message);
        }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章