具体介绍使用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 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,XmlSchemaXmlSchemaSet

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");

以上就是具体介绍使用xsd验证xml的代码分享的详细内容,更多请关注编程之家其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


xml怎么加入图片路径
rss源错误怎么解决
文件后缀xml是什么意思
xml格式电子发票怎么获取
xml格式是什么意思
rss是什么意思啊
xml格式电子发票怎么打开
rss订阅源是什么意思
rss源是什么
xml注释怎么写
php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念
xml文件介绍及使用
xml编程(一)-xml语法
XML文件结构和基本语法
第2章 包装类