xsd印证xml

xsd印证xml

xsd验证xml
来源:http://www.cnblogs.com/haitian/archive/2008/05/16/1200707.html
xsd验证xml


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 attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://www.contoso.com/books" xmlns:xs="http://www.w3.org/2001/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>

说明:
elementFormDefault 和 attributeFormDefault 都各有 2 个选项: unqualified, qualified. 那么它们分别都代表什么意思呢?默认值是 unqualified.

elementFormDefault=‘unqualified’ 时表示子元素不必使用命名空间前缀, 但这不等于说这些子元素是属于无命名空间, 所有被schema定义的element都应当属于目标命名空间, 这些子元素只是不直接位于目标命名空间, 而是从属于父*元素的目标命名空间, 这其实也就是说它们间接属于目标命名空间. 显然, 这种写法使得xml格式上简化了很多.

elementFormDefault=‘qualified’ 时表示子元素必须使用命名空间前缀, 当然, 这些子元素是位于目标命名空间之下.



备注:关于Xsd的其他的一些类或者实例

        StreamWriter ,StreamReader,XmlSchema,XmlSchemaSet

        Stream stream = new MemoryStream(); //当一个类的对象无法初始化时,可以考虑用它的继承类。

        FileStream fs = File.Open("117.xml",FileMode.OpenOrCreate,FileAccess.ReadWrite);
         
        TextReader tr1=new StreamReader("123.xml");

        TextReader tr2= new StringReader("asdfsadfsdf");