首頁  >  文章  >  後端開發  >  具體介紹使用xsd驗證xml的程式碼分享

具體介紹使用xsd驗證xml的程式碼分享

黄舟
黄舟原創
2017-03-23 16:55:102166瀏覽

Xsd

    XML結構定義 ( XML Schemas Definition )
    XML Schema
DTD的替代品。 XML Schema語言也就是XSD#。
    XML Schema
描述了XML文件的結構。可以用一個指定的XML Schema來驗證某個XML文檔,以檢查該XML文檔是否符合其要求。
  文件設計者可以透過
XML Schema指定一個XML文件所允許的結構和內容,並可據此檢查一個XML文件是否是有效的。 XML Schema本身是一個XML文檔,它符合XML語法結構。
  可以用通用的
XML#解析器解析它。
   
一個XML Schema會定義:文件中出現的元素、文件中出現的屬性、子元素、子元素的數量、子元素的順序、元素是否為空、元素和屬性的資料型態、元素或屬性的預設和固定值。

    XSD檔案的後綴名稱為.xsd
  
   ##在下面的程式碼範例中,上面的架構加入到 XmlReaderSettings 物件的 XmlSchemaSetSchemas 屬性中。 XmlReaderSettings 物件作為參數傳遞給驗證上述 XML 文件的 XmlReader 物件的 Create 方法。
  
XmlReaderSettings
物件的 ValidationType 屬性設定為 Schema,強制透過 XmlReader 物件的 Create 方法驗證 XML 文件。 ValidationEventHandler 新增至 XmlReaderSettings 物件以處理 XML 文件和架構驗證過程中發現的錯誤所引發的任何 Warning Error 事件。
  

#下面有一個範例:



#

using System;
using System.Xml;
using System.Xml.Schema;
using System.IO;
using System.Xml.Serialization;
using System.Text;

public class XmlSchemaSetExample
{
    static void Main()
    {

        XmlReaderSettings booksSettings = new XmlReaderSettings();
        booksSettings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd");
        booksSettings.ValidationType = ValidationType.Schema;
        booksSettings.ValidationEventHandler += new ValidationEventHandler(booksSettingsValidationEventHandler);

        MemoryStream ms = new MemoryStream();//定义一个数据流对象

        XmlDocument doc = new XmlDocument();

        doc.Load("contosoBooks.xml");

        doc.Save(ms);

        ms.Position = 0; //修改指针的位置

        XmlReader books = XmlReader.Create(ms,booksSettings);


        while (books.Read())
        {  }
     }

    static void booksSettingsValidationEventHandler(object sender, ValidationEventArgs e)
    {
        if (e.Severity == XmlSeverityType.Warning)
        {
            Console.Write("WARNING: ");
            Console.WriteLine(e.Message);
            Console.Read();
            
        }
        else if (e.Severity == XmlSeverityType.Error)
        {
            Console.Write("ERROR: ");
            Console.WriteLine(e.Message);
            Console.Read();
        }
    }
}
contosoBooks.xsd

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attribute
For
mDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://www.contoso.com/books" xmlns:xs="http://www.w3.org/2
001
/XMLSchema">
  <xs:element name="bookstore">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="book">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="title" type="xs:=string" />
              <xs:element name="author">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element minOccurs="0" name="name" type="xs:string" />
                    <xs:element minOccurs="0" name="first-name" type="xs:string" />
                    <xs:element minOccurs="0" name="last-name" type="xs:string" />
                  </xs:sequence>
                </xs:complexType>
              </xs:element>
              <xs:element name="price" type="xs:decimal" />
            </xs:sequence>
            <xs:attribute name="genre" type="xs:string" use="required" />
            <xs:attribute name="publicationdate" type="xs:date" use="required" />
            <xs:attribute name="ISBN" type="xs:string" use="required" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>


contosoBooks.xml
#

<?xml version="1.0" encoding="utf-8" ?>
<bookstore xmlns="http://www.contoso.com/books">
  <book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0">
    <title>The Autobiography of Benjamin Franklin</title>
    <author>
      <first-name>Benjamin</first-name>
      <last-name>Franklin</last-name>
    </author>
    <price>8.99</price>
  </book>
  <book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2">
    <title>The Confidence Man</title>
    <author>
      <first-name>Herman</first-name>
      <last-name>Melville</last-name>
    </author>
    <price>11.99</price>
  </book>
  <book genre="philosophy" publicationdate="1991-02-15" ISBN="1-861001-57-6">
    <title>The Gorgias</title>
    <author>
      <name>Plato</name>
    </author>
    <price>9.99</price>
  </book>
</bookstore>




####################################################################################################################################################################### # ########備註:關於Xsd的其他的一些類別或實例###### StreamWriter ,######StreamReader,###XmlSchema###,###XmlSchemaSet### #####################        Stream stream = new MemoryStream(); //當一個類別的物件無法初始化時,可以考慮用它的###繼承# ##類別。 ############        FileStream fs = File.Open("117.xml",FileMode.OpenOrCreate,FileAccess.ReadWrite);### #   123.xml");###############        TextReader tr2= new StringReader("asdfsadfsdf");################### ###

以上是具體介紹使用xsd驗證xml的程式碼分享的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn