public sealed class XmlSchemaCollection : ICollection, IEnumerable
|
Although this class stores both XML Schemas and XDR schemas, any method and property that takes or returns an XmlSchema applies to XML Schemas only.
This version of the product supports the World Wide Web Consortium (W3C) XML Schema recommendation located at http://www.w3.org/TR/xmlschema-1 and http://www.w3.org/TR/xmlschema-2 . An XML Schema must reference the W3C Schema namespace, http://www.w3.org/2001/XMLSchema in its schema element. See the XmlSchemaCollection.Add method for an example.
XmlSchemaCollection can be used by XmlValidatingReader for efficient data validation.
using System; using System.Xml; using System.Xml.Schema; using System.IO; public class ValidXSD { public static void Main() { XmlSchemaCollection sc = new XmlSchemaCollection(); sc.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); sc.Add(null, "books.xsd"); if(sc.Count > 0) { XmlTextReader tr = new XmlTextReader("notValidXSD.xml"); XmlValidatingReader rdr = new XmlValidatingReader(tr); rdr.ValidationType = ValidationType.Schema; rdr.Schemas.Add(sc); rdr.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); while (rdr.Read()); } } public static void ValidationCallBack(object sender, ValidationEventArgs e) { Console.WriteLine("Validation Error: {0}", e.Message); } }
ctor #1 | Overloaded:.ctor() Default constructor. This constructor is called by derived class constructors to initialize state in this type.Initializes a new instance of the XmlSchemaCollection class. |
ctor #2 | Overloaded:.ctor(XmlNameTable nametable) Initializes a new instance of the XmlSchemaCollection class with the specified XmlNameTable. The XmlNameTable is used when loading schemas. |
Count | Read-only Gets the number of namespaces defined in this collection. |
Item | Read-only Gets the XmlSchema associated with the given namespace URI. |
NameTable | Read-only Gets the default XmlNameTable used by the XmlSchemaCollection when loading new schemas. |
Add | Overloaded:Add(XmlSchema schema) Adds the XmlSchema to the collection. |
Add | Overloaded:Add(XmlSchemaCollection schema) Adds all the namespaces defined in the given collection (including their associated schemas) to this collection. |
Add | Overloaded:Add(string ns, string uri) Adds the schema located by the given URL into the schema collection. |
Add | Overloaded:Add(string ns, XmlReader reader) Adds the given schema into the schema collection. |
Contains | Overloaded:Contains(string ns) Gets a value indicating whether a schema with the specified namespace is in the collection. |
Contains | Overloaded:Contains(XmlSchema schema) Gets a value indicating whether the targetNamespace of the specified XmlSchema is in the collection. |
CopyTo | Copies all the XmlSchema objects from this collection into the given array starting at the given index. |
Equals (inherited from System.Object) |
See base class member description: System.Object.Equals Derived from System.Object, the primary base class for all objects. |
GetEnumerator | Provides support for the "for each" style iteration over the collection of schemas. |
GetHashCode (inherited from System.Object) |
See base class member description: System.Object.GetHashCode Derived from System.Object, the primary base class for all objects. |
GetType (inherited from System.Object) |
See base class member description: System.Object.GetType Derived from System.Object, the primary base class for all objects. |
ToString (inherited from System.Object) |
See base class member description: System.Object.ToString Derived from System.Object, the primary base class for all objects. |
ValidationEventHandler | Sets an event handler for receiving information about the XML-Data Reduced (XDR) and XML Schema definition language (XSD) schema validation errors. |
Finalize (inherited from System.Object) |
See base class member description: System.Object.Finalize Derived from System.Object, the primary base class for all objects. |
MemberwiseClone (inherited from System.Object) |
See base class member description: System.Object.MemberwiseClone Derived from System.Object, the primary base class for all objects. |
Hierarchy:
public XmlSchemaCollection(); |
public XmlSchemaCollection( |
nametable
public int Count {get;}
|
public XmlSchema this[string ns] {get;}
|
ns
if (xsc.Contains("urn:bookstore-schema")) { XmlSchema schema = xsc["urn:bookstore-schema"]; StringWriter sw = new StringWriter(); XmlTextWriter xmlWriter = new XmlTextWriter(sw); xmlWriter.Formatting = Formatting.Indented; xmlWriter.Indentation = 2; schema.Write(xmlWriter); Console.WriteLine(sw.ToString()); }
public XmlNameTable NameTable {get;}
|
schema
If the schema contains include and import elements that reference other namespaces, the schemas for these other namespaces are loaded for validation purposes only. Unlike the original schema, these other schemas are not explicitly added to the schema collection. As a result, they are not accessible using any of the collection methods or properties.
public void Add( |
schema
ns
uri
Exception Type | Condition |
---|---|
XmlException | The schema is not a valid schema. |
schemaColl.Add("urn:author", "authors.xsd"); schemaColl.Add("urn:author", "names.xsd");If ns is null and the schema being added is an XML Schema, the Add method uses the targetNamespace defined in the XML Schema to identify the schema in the collection.
If you are adding an XML Schema and the schema contains include and import elements that reference other namespaces, the schemas for these other namespaces are loaded for validation purposes only. Unlike the original schema, these other schemas are not explicitly added to the schema collection. As a result, they are not accessible using any of the collection methods or properties.
If you are adding an XDR schema and the schema references other schemas using the x-schema attribute, these schemas are not loaded for validation purposes and are not added to the schema collection.
using System; using System.IO; using System.Xml; using System.Xml.Schema; public class SchemaCollectionSample { private const String doc1 = "booksSchema.xml"; private const String doc2 = "booksSchemaFail.xml"; private const String doc3 = "newbooks.xml"; private const String schema = "books.xsd"; private const String schema1 = "schema1.xdr"; private XmlTextReader reader=null; private XmlValidatingReader vreader = null; private Boolean m_success = true; public SchemaCollectionSample () { //Load the schema collection. XmlSchemaCollection xsc = new XmlSchemaCollection(); xsc.Add("urn:bookstore-schema", schema); //XSD schema xsc.Add("urn:newbooks-schema", schema1); //XDR schema //Validate the files using schemas stored in the collection. Validate(doc1, xsc); //Should pass. Validate(doc2, xsc); //Should fail. Validate(doc3, xsc); //Should fail. } public static void Main () { SchemaCollectionSample validation = new SchemaCollectionSample(); } private void Validate(String filename, XmlSchemaCollection xsc) { m_success = true; Console.WriteLine(); Console.WriteLine("Validating XML file {0}...", filename.ToString()); reader = new XmlTextReader (filename); //Create a validating reader. vreader = new XmlValidatingReader (reader); //Validate using the schemas stored in the schema collection. vreader.Schemas.Add(xsc); //Set the validation event handler vreader.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack); //Read and validate the XML data. while (vreader.Read()){} Console.WriteLine ("Validation finished. Validation {0}", (m_success==true ? "successful" : "failed")); Console.WriteLine(); //Close the reader. vreader.Close(); } public void ValidationCallBack (object sender, ValidationEventArgs args) { m_success = false; Console.Write("\r\n\tValidation error: " + args.Message); } }
The sample uses the following five input files:
booksSchema.xml
<?xml version='1.0'?> <bookstore xmlns="urn:bookstore-schema"> <book genre="autobiography"> <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"> <title>The Confidence Man</title> <author> <first-name>Herman</first-name> <last-name>Melville</last-name> </author> <price>11.99</price> </book> </bookstore>
booksSchemaFail.xml
<?xml version='1.0'?> <bookstore xmlns="urn:bookstore-schema"> <book> <author> <first-name>Benjamin</first-name> <last-name>Franklin</last-name> </author> </book> <book genre="novel"> <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"> <title>The Gorgias</title> <author> <name>Plato</name> </author> <price>9.99</price> </book> </bookstore>
newbooks.xml
<?xml version='1.0'?> <bookstore xmlns="urn:newbooks-schema"> <book genre="novel" style="hardcover"> <title>The Handmaid's Tale</title> <author> <first-name>Margaret</first-name> <last-name>Atwood</last-name> </author> <price>19.95</price> </book> <book genre="novel" style="other"> <title>The Poisonwood Bible</title> <author> <first-name>Barbara</first-name> <last-name>Kingsolver</last-name> </author> <price>11.99</price> </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>
schema1.xdr
<?xml version="1.0"?> <Schema xmlns="urn:schemas-microsoft-com:xml-data" xmlns:dt="urn:schemas-microsoft-com:datatypes"> <ElementType name="first-name" content="textOnly"/> <ElementType name="last-name" content="textOnly"/> <ElementType name="name" content="textOnly"/> <ElementType name="price" content="textOnly" dt:type="fixed.14.4"/> <ElementType name="author" content="eltOnly" order="one"> <group order="seq"> <element type="name"/> </group> <group order="seq"> <element type="first-name"/> <element type="last-name"/> </group> </ElementType> <ElementType name="title" content="textOnly"/> <AttributeType name="genre" dt:type="string"/> <AttributeType name="style" dt:type="enumeration" dt:values="paperback hardcover"/> <ElementType name="book" content="eltOnly"> <attribute type="genre" required="yes"/> <attribute type="style" required="yes"/> <element type="title"/> <element type="author"/> <element type="price"/> </ElementType> <ElementType name="bookstore" content="eltOnly"> <element type="book"/> </ElementType> </Schema>
ns
reader
Exception Type | Condition |
---|---|
XmlException | The schema is not a valid schema. |
If ns is null and the schema being added is an XML Schema, the Add method uses the targetNamespace defined in the XML Schema to identify the schema in the collection.
If you are adding an XML Schema and the schema contains include and import elements that reference other namespaces, the schemas for these other namespaces are loaded for validation purposes only. Unlike the original schema, these other schemas are not explicitly added to the schema collection. As a result, they are not accessible using any of the collection methods or properties.
If you are adding an XDR schema and the schema references other schemas using the x-schema attribute, these schemas are not loaded for validation purposes and are not added to the schema collection.
ns
if (xsc.Contains("urn:bookstore-schema")) { XmlSchema schema = xsc["urn:bookstore-schema"]; StringWriter sw = new StringWriter(); XmlTextWriter xmlWriter = new XmlTextWriter(sw); xmlWriter.Formatting = Formatting.Indented; xmlWriter.Indentation = 2; schema.Write(xmlWriter); Console.WriteLine(sw.ToString()); }
schema
public void CopyTo( |
array
index
~XmlSchemaCollection(); |
public XmlSchemaCollectionEnumerator GetEnumerator(); |
public void DisplaySchemas(XmlSchemaCollection xsc) { XmlSchemaCollectionEnumerator ienum = xsc.GetEnumerator(); while (ienum.MoveNext()) { XmlSchema schema = ienum.Current; StringWriter sw = new StringWriter(); XmlTextWriter writer = new XmlTextWriter(sw); writer.Formatting = Formatting.Indented; writer.Indentation = 2; schema.Write(writer); Console.WriteLine(sw.ToString()); } }
public virtual int GetHashCode(); |
public Type GetType(); |
protected object MemberwiseClone(); |
public virtual string ToString(); |
public event ValidationEventHandler ValidationEventHandler;
|
using System; using System.IO; using System.Xml; using System.Xml.Schema; public class Sample { public static void Main (){ //Create the schema collection. XmlSchemaCollection xsc = new XmlSchemaCollection(); //Set an event handler to manage invalid schemas. xsc.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack); //Add the schema to the collection. xsc.Add(null, "invalid.xsd"); } //Display the schema error information. public static void ValidationCallBack (object sender, ValidationEventArgs args){ Console.WriteLine("Invalid XSD schema: " + args.Exception.Message); } }The preceding example uses the file, invalid.xsd, as input.
<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema' > <xsd:complexType name="personName"> <xsd:sequence> <xsd:element name="title" minOccurs="0" maxOccurs="1"/> <xsd:element name="forename" minOccurs="0" maxOccurs="unbounded"/> <xsd:element name="surname"/> </xsd:sequence> </xsd:complexType> <xsd:complexType name="simpleName"> <xsd:complexContent> <xsd:restriction base="personName"> <xsd:sequence> <xsd:element name="title" minOccurs="0" maxOccurs="0"/> <xsd:element name="firstname" minOccurs="1" maxOccurs="1"/> <xsd:element name="surname"/> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType> </xsd:schema>