Validação de XSD (esquema XML) com XmlSchemaCollectionXML Schema (XSD) Validation with XmlSchemaCollection

Você pode usar o XmlSchemaCollection para validar um documento XML com esquemas XSD.You can use the XmlSchemaCollection to validate an XML document against XML Schema definition language (XSD) schemas. O XmlSchemaCollection melhora o desempenho armazenando esquemas na coleção, de forma que não sejam carregados na memória sempre que ocorra uma validação.The XmlSchemaCollection improves performance by storing schemas in the collection so they are not loaded into memory each time validation occurs. Se o esquema existir na coleção de esquema, o atributo schemaLocation será usado para pesquisar o esquema na coleção.If the schema exists in the schema collection, the schemaLocation attribute is used to look up the schema in the collection.

Importante

A classe XmlSchemaCollection agora está obsoleta e foi substituída pela classe XmlSchemaSet.The XmlSchemaCollection class is now obsolete and has been replaced with the XmlSchemaSet class. Para saber mais sobre a classe XmlSchemaSet, veja XmlSchemaSet para compilação de esquema.For more information about the XmlSchemaSet class see, XmlSchemaSet for Schema Compilation.

O exemplo a seguir mostra o elemento raiz de um arquivo de dados.The following example shows the root element of a data file.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"  
    xmlns="urn:bookstore-schema"  
    elementFormDefault="qualified"  
    targetNamespace="urn:bookstore-schema">  

Para esse exemplo, o valor do atributo targetNamespace é urn:bookstore-schema, que é o mesmo namespace usado ao adicionar o esquema ao XmlSchemaCollection.For this example, the value of the targetNamespace attribute is urn:bookstore-schema, which is the same namespace that is used when adding the schema to the XmlSchemaCollection.

O exemplo de código a seguir adiciona um esquema XML ao XmlSchemaCollection.The following code example adds an XML Schema to the XmlSchemaCollection.

Dim xsc As New XmlSchemaCollection()  
' XML Schema.  
xsc.Add("urn:bookstore-schema", schema)
reader = New XmlTextReader(filename)  
vreader = New XmlValidatingReader(reader)  
vreader.Schemas.Add(xsc)  
XmlSchemaCollection xsc = new XmlSchemaCollection();  
// XML Schema.  
xsc.Add("urn:bookstore-schema", schema);  
reader = new XmlTextReader (filename);  
vreader = new XmlValidatingReader (reader);  
vreader.Schemas.Add(xsc);  

O atributo targetNamespace geralmente é usado quando você adiciona a propriedade namespaceURI no método Add para o XmlSchemaCollection.The targetNamespace attribute is generally used when you add the namespaceURI property in the Add method for the XmlSchemaCollection. Você pode especificar uma referência nula antes de adicionar o esquema ao XmlSchemaCollection.You can specify a null reference before adding the schema to the XmlSchemaCollection. Uma cadeia de caracteres vazia ("") deve ser usada para esquemas sem um namespace.An empty string ("") should be used for schemas without a namespace. O XmlSchemaCollection pode ter apenas um esquema sem um namespace.The XmlSchemaCollection can have only one schema without a namespace.

O exemplo de código a seguir adiciona um esquema XML, HeadCount.xsd, ao XmlSchemaCollection e valida HeadCount.xml.The following code example adds an XML Schema, HeadCount.xsd, to the XmlSchemaCollection and validates HeadCount.xml.

Imports System  
Imports System.IO  
Imports System.Xml  
Imports System.Xml.Schema  
  
Namespace ValidationSample  
  
   Class Sample  
  
      Public Shared Sub Main()  
         Dim tr As New XmlTextReader("HeadCount.xml")  
         Dim vr As New XmlValidatingReader(tr)  
  
         vr.Schemas.Add("xsdHeadCount", "HeadCount.xsd")  
         vr.ValidationType = ValidationType.Schema  
         AddHandler vr.ValidationEventHandler, AddressOf ValidationHandler  
  
         While vr.Read()  
         End While  
         Console.WriteLine("Validation finished")  
      End Sub  
      ' Main  
  
      Public Shared Sub ValidationHandler(sender As Object, args As ValidationEventArgs)  
         Console.WriteLine("***Validation error")  
         Console.WriteLine("Severity:{0}", args.Severity)  
         Console.WriteLine("Message:{0}", args.Message)  
      End Sub  
      ' ValidationHandler  
   End Class  
   ' Sample  
End Namespace  
' ValidationSample  
using System;  
using System.IO;  
using System.Xml;  
using System.Xml.Schema;  
  
namespace ValidationSample  
{  
   class Sample  
   {  
      public static void Main()  
      {  
         XmlTextReader tr = new XmlTextReader("HeadCount.xml");  
         XmlValidatingReader vr = new XmlValidatingReader(tr);  
  
         vr.Schemas.Add("xsdHeadCount", "HeadCount.xsd");  
         vr.ValidationType = ValidationType.Schema;  
         vr.ValidationEventHandler += new ValidationEventHandler (ValidationHandler);  
  
         while(vr.Read());  
         Console.WriteLine("Validation finished");  
      }  
  
      public static void ValidationHandler(object sender, ValidationEventArgs args)  
      {  
         Console.WriteLine("***Validation error");  
         Console.WriteLine("\tSeverity:{0}", args.Severity);  
         Console.WriteLine("\tMessage  :{0}", args.Message);  
      }  
   }  
}  

O seguinte descreve o conteúdo do arquivo de entrada, HeadCount.xml, a ser validado.The following outlines the contents of the input file, HeadCount.xml, to be validated.

<!--Load HeadCount.xsd in SchemaCollection for Validation-->  
<hc:HeadCount xmlns:hc='xsdHeadCount'>  
   <Name>Waldo Pepper</Name>  
   <Name>Red Pepper</Name>  
</hc:HeadCount>  

O seguinte descreve o conteúdo do arquivo de esquema XML, HeadCount.xsd, com o qual validar.The following outlines the contents of the XML Schema file, HeadCount.xsd, to be validated against.

<xs:schema xmlns="xsdHeadCount" targetNamespace="xsdHeadCount" xmlns:xs="http://www.w3.org/2001/XMLSchema">  
   <xs:element name='HeadCount' type="HEADCOUNT"/>  
   <xs:complexType name="HEADCOUNT">  
      <xs:sequence>  
         <xs:element name='Name' type='xs:string' maxOccurs='unbounded'/>  
      </xs:sequence>  
      <xs:attribute name='division' type='xs:int' use='optional' default='8'/>  
   </xs:complexType>  
</xs:schema>  

O exemplo de código a seguir cria um XmlValidatingReader que utiliza um XmlTextReader.The following code example creates an XmlValidatingReader that takes an XmlTextReader. O arquivo de entrada, sample4.xml, é validado com o esquema XML, sample4.xsd.The input file, sample4.xml, is validated against the XML Schema, sample4.xsd.

Dim tr As New XmlTextReader("sample4.xml")  
Dim vr As New XmlValidatingReader(tr)  
vr.ValidationType = ValidationType.Schema  
vr.Schemas.Add("datatypesTest", "sample4.xsd")  
AddHandler vr.ValidationEventHandler, AddressOf ValidationCallBack  
While vr.Read()  
   Console.WriteLine("NodeType: {0} NodeName: {1}", vr.NodeType, vr.Name)  
End While  
XmlTextReader tr = new XmlTextReader("sample4.xml");  
XmlValidatingReader vr = new XmlValidatingReader(tr);  
vr.ValidationType = ValidationType.Schema;  
        vr.Schemas.Add("datatypesTest", "sample4.xsd");  
vr.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);  
while(vr.Read()) {  
    Console.WriteLine("NodeType: {0} NodeName: {1}", vr.NodeType, vr.Name);  
    }  

O seguinte descreve o conteúdo do arquivo de entrada, sample4.xml, a ser validado.The following outlines the contents of the input file, sample4.xml, to be validated.

<datatypes xmlns="datatypesTest">  
    <number>  
        <number_1>123</number_1>  
    </number>  
</datatypes>  

O seguinte descreve o conteúdo do arquivo de esquema XML, sample4.xml, com o qual validar.The following outlines the contents of the XML Schema file, sample4.xsd, to be validated against.

<xs:schema
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:tns="datatypesTest"
    targetNamespace="datatypesTest"  
    elementFormDefault="qualified">  
  
<xs:element name = "datatypes">  
  <xs:complexType>  
    <xs:all>  
        <xs:element name="number">  
            <xs:complexType>  
                <xs:sequence>  
                    <xs:element name="number_1" type="xs:decimal" maxOccurs="unbounded"/>  
                </xs:sequence>  
            </xs:complexType>  
        </xs:element>  
    </xs:all>  
  </xs:complexType>  
</xs:element>  
</xs:schema>  

Consulte tambémSee also