ホームページ  >  記事  >  バックエンド開発  >  xsd を使用して XML を検証するコード共有の詳細な紹介

xsd を使用して XML を検証するコード共有の詳細な紹介

黄舟
黄舟オリジナル
2017-03-23 16:55:102165ブラウズ

XML Schema

言語もXSDです。
XML スキーマ
は、XML ドキュメントの構造を記述します。特定の XML ドキュメントを、指定された XML スキーマ に対して検証して、XML
ドキュメントがその要件を満たしているかどうかを確認できます。 ドキュメント設計者は、XML スキーマ を通じて XML ドキュメントで許可される構造とコンテンツを指定でき、これに基づいて XML ドキュメントが有効かどうかを確認できます。 XML Schema自体は、
XML構文構造に準拠するXMLドキュメントです。 ユニバーサル XML パーサーで解析できます。 XML スキーマ は、ドキュメントに表示される要素、ドキュメントに表示される属性、サブ要素、サブ要素の数、サブ要素の順序、要素は空であり、要素と属性のデータ型、要素、またはプロパティのデフォルト値と固定値です。

XSDファイルの拡張子は.xsdです。

以下のコード例では、上記のスキーマが XmlReaderSettings オブジェクトの XmlSchemaSetSchemas プロパティに追加されます。 XmlReaderSettings オブジェクトは、上記の XML ドキュメントを検証する XmlReader オブジェクトの Create メソッドにパラメーターとして渡されます。

XmlReaderSettings オブジェクトの ValidationType プロパティは Schema に設定され、 XmlReader オブジェクトの Create メソッドを通じて XML ドキュメントの検証が強制されます。 ValidationEventHandler に追加します
これが例です:

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
ストリーム ストリーム = 新しい MemoryStream (); //クラスのオブジェクトを初期化できない場合は、その inherited
クラスの使用を検討できます。

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

TextReader tr2= 新しいStringReader("asdfsadfsdf");

以上がxsd を使用して XML を検証するコード共有の詳細な紹介の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。