.NET Framework 开发人员指南
使用 XmlSchemaSet 进行验证
更新:November 2007
XmlSchemaSet 是可以存储 XML 架构定义语言 (XSD) 架构的缓存或库。XmlSchemaSet 通过将架构缓存在内存中,而不是从文件或 URL 访问架构,从而提高性能。 XmlSchemaSet 中的每个架构通过命名空间 URI 和架构位置来标识,命名空间 URI 和架构位置在架构添加到 XmlSchemaSet 时指定。 Schemas 属性分配要使用的 XmlSchemaSet 对象。
示例
using System; using System.Xml; using System.Xml.Schema; using System.IO; public class Sample { public static void Main() { // Create the XmlSchemaSet class. XmlSchemaSet sc = new XmlSchemaSet(); // Add the schema to the collection. sc.Add("urn:bookstore-schema", "books.xsd"); // Set the validation settings. XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.Schemas = sc; settings.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack); // Create the XmlReader object. XmlReader reader = XmlReader.Create("booksSchemaFail.xml", settings); // Parse the file. while (reader.Read()); } // Display any validation errors. private static void ValidationCallBack(object sender, ValidationEventArgs e) { Console.WriteLine("Validation Error: {0}", e.Message); } }
输入
示例使用下列两个输入文件。
booksSchemaFail.xml
<?xml version='1.0'?> <bookstore xmlns="urn:bookstore-schema"> <book> <author> <first-name>Benjaminfirst-name> <last-name>Franklinlast-name> author> book> <book genre="novel"> <title>The Confidence Mantitle> <author> <first-name>Hermanfirst-name> <last-name>Melvillelast-name> author> <price>11.99price> book> <book genre="philosophy"> <title>The Gorgiastitle> <author> <name>Platoname> author> <price>9.99price> book> bookstore>books.xsd
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:bookstore-schema" elementFormDefault="qualified" targetNamespace="urn:bookstore-schema"> <xsd:element name="bookstore" type="bookstoreType"/> <xsd:complexType name="bookstoreType"> <xsd:sequence maxOccurs="unbounded"> <xsd:element name="book" type="bookType"/> xsd:sequence> xsd:complexType> <xsd:complexType name="bookType"> <xsd:sequence> <xsd:element name="title" type="xsd:string"/> <xsd:element name="author" type="authorName"/> <xsd:element name="price" type="xsd:decimal"/> xsd:sequence> <xsd:attribute name="genre" type="xsd:string"/> xsd:complexType> <xsd:complexType name="authorName"> <xsd:sequence> <xsd:element name="first-name" type="xsd:string"/> <xsd:element name="last-name" type="xsd:string"/> xsd:sequence> xsd:complexType> xsd:schema>输出
验证错误: 命名空间“urn:bookstore-schema”中的元素“book”在命名空间“urn:bookstore-schema”中具有无效子元素“author”。应为命名空间“urn:bookstore-schema”中的“title”。
验证错误: 命名空间“urn:bookstore-schema”中的元素“author”在命名空间“urn:bookstore-schema”中具有无效子元素“name”。应为命名空间“urn:bookstore-schema”中的“first-name”。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/12476590/viewspace-504264/ ,如需转载,请注明出处,否则将追究法律责任。