System.Xml.Schema.XmlSchemaCollection Class

Assembly: System.Xml.dll
Namespace: System.Xml.Schema
Summary
Contains a cache of XML Schema definition language (XSD) and XML-Data Reduced (XDR) schemas. This class cannot be inherited.
C# Syntax:
public sealed class XmlSchemaCollection : ICollection, IEnumerable
Remarks
Schemas are loaded using the XmlSchemaCollection.Add method, at which time the schema is associated with a namespace URI. For XML Schemas, this will typically be the targetNamespace property of the schema.

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.

Example
The following example validates an XML document using the XmlSchemaCollection.
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);
  }
}

    
See also:
System.Xml.Schema Namespace

System.Xml.Schema.XmlSchemaCollection Member List:

Public Constructors
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.
Public Properties
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.
Public Methods
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.
Public Events
ValidationEventHandler Sets an event handler for receiving information about the XML-Data Reduced (XDR) and XML Schema definition language (XSD) schema validation errors.
Protected Methods
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:


System.Xml.Schema.XmlSchemaCollection Member Details

Overloaded ctor #1
Summary
Initializes a new instance of the XmlSchemaCollection class.

Default constructor. This constructor is called by derived class constructors to initialize state in this type.
C# Syntax:
public XmlSchemaCollection();

Return to top


Overloaded ctor #2
Summary
Initializes a new instance of the XmlSchemaCollection class with the specified XmlNameTable. The XmlNameTable is used when loading schemas.
C# Syntax:
public XmlSchemaCollection(
   XmlNameTable nametable
);
Parameters:

nametable

The XmlNameTable to use.

Return to top


Property: Count (read-only)
Summary
Gets the number of namespaces defined in this collection.
C# Syntax:
public int Count {get;}

Return to top


Property: Item (read-only)
Summary
Gets the XmlSchema associated with the given namespace URI.
C# Syntax:
public XmlSchema this[string ns] {get;}
Parameters:

ns

The namespace URI associated with the schema you want to return. This will typically be the targetNamespace of the schema.

Example
The following example checks to see if a schema is in the collection. If it is, it displays the schema.
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());
}

    

Return to top


Property: NameTable (read-only)
Summary
Gets the default XmlNameTable used by the XmlSchemaCollection when loading new schemas.
C# Syntax:
public XmlNameTable NameTable {get;}
See also:
XmlNameTable

Return to top


Overloaded Method: Add(
   XmlSchema schema
)
Summary
Adds the XmlSchema to the collection.
C# Syntax:
public XmlSchema Add(
   XmlSchema schema
);
Parameters:

schema

The XmlSchema to add to the collection.

Return Value:
The XmlSchema object.
Remarks
The targetNamespace attribute is used to identify this 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.

See also:
XmlSchema

Return to top


Overloaded Method: Add(
   XmlSchemaCollection schema
)
Summary
Adds all the namespaces defined in the given collection (including their associated schemas) to this collection.
C# Syntax:
public void Add(
   XmlSchemaCollection schema
);
Parameters:

schema

The XmlSchemaCollection you want to add to this collection.

Return to top


Overloaded Method: Add(
   string ns,
   string uri
)
Summary
Adds the schema located by the given URL into the schema collection.
C# Syntax:
public XmlSchema Add(
   string ns,
   string uri
);
Parameters:

ns

The namespace URI associated with the schema. For XML Schema Definition language (XSD) schemas, this will typically be the targetNamespace.

uri

The URL that specifies the schema to load.

Return Value:
The XmlSchema added to the schema collection; null if the the schema being added is an XDR schema or if there are compilation errors in the schema.
Exceptions
Exception Type Condition
XmlException The schema is not a valid schema.
Remarks
If ns has already been associated with another schema in the collection, the schema being added replaces the original schema in the collection. For example, in the following C# code, authors.xsd is removed from the collection and names.xsd is added.
              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.

Example
The following example validates three XML files using schemas stored in the XmlSchemaCollection.

 
 
 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>

    

Return to top


Overloaded Method: Add(
   string ns,
   XmlReader reader
)
Summary
Adds the given schema into the schema collection.
C# Syntax:
public XmlSchema Add(
   string ns,
   XmlReader reader
);
Parameters:

ns

The namespace URI associated with the schema. For XML Schema definition language (XSD) schemas, this will typically be the targetNamespace.

reader

XmlReader containing the schema to add.

Return Value:
The XmlSchema added to the schema collection; null if the schema being added is an XML-Data Reduced (XDR) schema or if there are compilation errors in the schema.
Exceptions
Exception Type Condition
XmlException The schema is not a valid schema.
Remarks
If ns has already been associated with another schema in the collection, the schema being added replaces the original schema in the collection.

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.

Return to top


Overloaded Method: Contains(
   string ns
)
Summary
Gets a value indicating whether a schema with the specified namespace is in the collection.
C# Syntax:
public bool Contains(
   string ns
);
Parameters:

ns

The namespace URI associated with the schema. For XML Schema Definition language (XSD) schemas, this will typically be the target namespace.

Return Value:
true if a schema with the specified namespace is in the collection; otherwise, false.
Example
The following example checks to see if a schema is in the collection. If it is, it displays the schema.
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());
}

    

Return to top


Overloaded Method: Contains(
   XmlSchema schema
)
Summary
Gets a value indicating whether the targetNamespace of the specified XmlSchema is in the collection.
C# Syntax:
public bool Contains(
   XmlSchema schema
);
Parameters:

schema

The XmlSchema object.

Return Value:
true if there is a schema in the collection with the same targetNamespace; otherwise, false.

Return to top


Method: CopyTo(
   XmlSchema[] array,
   int index
)
Summary
Copies all the XmlSchema objects from this collection into the given array starting at the given index.
C# Syntax:
public void CopyTo(
   XmlSchema[] array,
   int index
);
Parameters:

array

The array to copy the objects to.

index

The index in array where copying will begin.

Return to top


Method: Equals(
   object obj
)
Inherited
See base class member description: System.Object.Equals
C# Syntax:
public virtual bool Equals(
   object obj
);

For more information on members inherited from System.Object click on the link above.

Return to top


Method: Finalize()
Inherited
See base class member description: System.Object.Finalize
C# Syntax:
~XmlSchemaCollection();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetEnumerator()
Summary
Provides support for the "for each" style iteration over the collection of schemas.
C# Syntax:
public XmlSchemaCollectionEnumerator GetEnumerator();
Return Value:
An enumerator for iterating over all schemas in the current collection.
Example
The following example displays each of the XML Schema definition language (XSD) schemas in the schema collection.
    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());  

      }
    }

    
See also:
XmlSchemaCollectionEnumerator

Return to top


Method: GetHashCode()
Inherited
See base class member description: System.Object.GetHashCode
C# Syntax:
public virtual int GetHashCode();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetType()
Inherited
See base class member description: System.Object.GetType
C# Syntax:
public Type GetType();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: MemberwiseClone()
Inherited
See base class member description: System.Object.MemberwiseClone
C# Syntax:
protected object MemberwiseClone();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: ToString()
Inherited
See base class member description: System.Object.ToString
C# Syntax:
public virtual string ToString();

For more information on members inherited from System.Object click on the link above.

Return to top


Event: ValidationEventHandler
Summary
Sets an event handler for receiving information about the XML-Data Reduced (XDR) and XML Schema definition language (XSD) schema validation errors.
C# Syntax:
public event ValidationEventHandler ValidationEventHandler;
Remarks
These events occur when the schemas are added to the collection. If an event handler is not provided, an XmlSchemaException is thrown on any validation errors where the ValidationEventArgs.Severity is XmlSeverityType.Error. To specify an event handler, define a callback function and add it to the ValidationEventHandler.
Example
The following example shows how to set an event handler to handle invalid XML Schemas.
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>

    

Return to top


Top of page

Copyright (c) 2002 Microsoft Corporation. All rights reserved.