如何使用xsd验证xml

发布时间:2021-03-12 11:30:53 作者:小新
来源:亿速云 阅读:235

这篇文章主要介绍如何使用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验证xml”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. dubbo.xsd的配置
  2. dtd与xsd去区别

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

xsd xml

上一篇:怎么使用XML将机器内码转换为人们能够理解的信息

下一篇:phonegap如何操作数据库

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》