XmlValidatingReader Construtores

Definição

Inicializa uma nova instância da classe XmlValidatingReader.

Sobrecargas

XmlValidatingReader(XmlReader)

Inicializa uma nova instância da classe XmlValidatingReader que valida o conteúdo retornado do XmlReader fornecido.

XmlValidatingReader(Stream, XmlNodeType, XmlParserContext)

Inicializa uma nova instância da classe XmlValidatingReader com os valores especificados.

XmlValidatingReader(String, XmlNodeType, XmlParserContext)

Inicializa uma nova instância da classe XmlValidatingReader com os valores especificados.

XmlValidatingReader(XmlReader)

Inicializa uma nova instância da classe XmlValidatingReader que valida o conteúdo retornado do XmlReader fornecido.

public:
 XmlValidatingReader(System::Xml::XmlReader ^ reader);
public XmlValidatingReader (System.Xml.XmlReader reader);
new System.Xml.XmlValidatingReader : System.Xml.XmlReader -> System.Xml.XmlValidatingReader
Public Sub New (reader As XmlReader)

Parâmetros

reader
XmlReader

O XmlReader a ler lido durante a validação. A implementação atual dá suporte somente a XmlTextReader.

Exceções

O leitor especificado não é um XmlTextReader.

Exemplos

O exemplo a seguir valida dois documentos.

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
using namespace System::Xml::Schema;
public ref class Sample
{
private:
   static Boolean m_success = true;

public:
   Sample()
   {
      
      // Validate the document using an external XSD schema.  Validation should fail.
      Validate( "notValidXSD.xml" );
      
      // Validate the document using an inline XSD. Validation should succeed.
      Validate( "inlineXSD.xml" );
   }


private:

   // Display the validation error.
   void ValidationCallBack( Object^ /*sender*/, ValidationEventArgs^ args )
   {
      m_success = false;
      Console::WriteLine( "\r\n\tValidation error: {0}", args->Message );
   }

   void Validate( String^ filename )
   {
      m_success = true;
      Console::WriteLine( "\r\n******" );
      Console::WriteLine( "Validating XML file {0}", filename );
      XmlTextReader^ txtreader = gcnew XmlTextReader( filename );
      XmlValidatingReader^ reader = gcnew XmlValidatingReader( txtreader );
      
      // Set the validation event handler
      reader->ValidationEventHandler += gcnew ValidationEventHandler( this, &Sample::ValidationCallBack );
      
      // Read XML data
      while ( reader->Read() )
      {}

      Console::WriteLine( "Validation finished. Validation {0}", (m_success == true ? (String^)"successful!" : "failed.") );
      
      // Close the reader.
      reader->Close();
   }

};

int main()
{
   Sample^ validation = gcnew Sample;
}

using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;

public class Sample
{

  private Boolean m_success = true;

  public Sample ()
  {
      //Validate the document using an external XSD schema.  Validation should fail.
      Validate("notValidXSD.xml");

      //Validate the document using an inline XSD. Validation should succeed.
      Validate("inlineXSD.xml");
  }

  public static void Main ()
  {
      Sample validation = new Sample();
  }

  private void Validate(String filename)
  {
      m_success = true;
      Console.WriteLine("\r\n******");
      Console.WriteLine("Validating XML file " + filename.ToString());
      XmlTextReader txtreader = new XmlTextReader (filename);
      XmlValidatingReader reader = new XmlValidatingReader (txtreader);

      // Set the validation event handler
      reader.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);

      // Read XML data
      while (reader.Read()){}
      Console.WriteLine ("Validation finished. Validation {0}", (m_success==true ? "successful!" : "failed."));

      //Close the reader.
      reader.Close();
  }

  //Display the validation error.
  private void ValidationCallBack (object sender, ValidationEventArgs args)
  {
     m_success = false;
     Console.WriteLine("\r\n\tValidation error: " + args.Message );
  }
}
Imports System.IO
Imports System.Xml
Imports System.Xml.Schema

public class Sample

  private m_success as Boolean = true

  public sub New ()
      'Validate the document using an external XSD schema.  Validation should fail.
      Validate("notValidXSD.xml") 

      'Validate the document using an inline XSD. Validation should succeed.
      Validate("inlineXSD.xml")
  end sub

  public shared sub Main ()
 
      Dim validation as Sample = new Sample()
  end sub

  private sub Validate(filename as String)

      m_success = true
      Console.WriteLine()
      Console.WriteLine("******")
      Console.WriteLine("Validating XML file " + filename.ToString())
      Dim txtreader as XmlTextReader = new XmlTextReader (filename)
      Dim reader as XmlValidatingReader = new XmlValidatingReader (txtreader)

      ' Set the validation event handler
      AddHandler reader.ValidationEventHandler, AddressOf ValidationCallBack

      ' Read XML data
      while (reader.Read())
      end while
      Console.WriteLine ("Validation finished. Validation {0}", IIf(m_success, "successful!", "failed."))

      'Close the reader.
      reader.Close()
  end sub

  'Display the validation error.
  Private sub ValidationCallBack (sender as object, args as ValidationEventArgs)

     m_success = false
     Console.WriteLine()
     Console.WriteLine("  Validation error: " + args.Message )
  end sub
end class

O exemplo usa os seguintes arquivos de entrada:

notValidXSD.xml

<?xml version='1.0'?>
<bookstore xmlns="urn:bookstore-schema"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="urn:bookstore-schema books.xsd">
  <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>
</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>

inlineXSD.xml

<store-data>
<!--Inline XSD schema-->
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <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="price"  type="xsd:decimal"/>
  </xsd:sequence>
  <xsd:attribute name="genre" type="xsd:string"/>
 </xsd:complexType>
</xsd:schema>
<!-- end of schema -->

<bookstore>
  <book genre="novel">
    <title>Pride And Prejudice</title>
    <price>19.95</price>
  </book>
</bookstore>
</store-data>

Comentários

Observação

A XmlValidatingReader classe está obsoleta no .NET Framework 2.0. Você pode criar uma instância de validação XmlReader usando a XmlReaderSettings classe e o Create método. Para obter mais informações, consulte a seção de Comentários da página de referência XmlReader.

Todos os nós retornados do determinado XmlReader também são retornados desse leitor de validação, portanto, não há perda de informações no processo. Novos nós não retornados do leitor subjacente podem ser adicionados por esse leitor (por exemplo, atributos padrão e filhos de uma referência de entidade). Todas as propriedades definidas no determinado XmlTextReader também se aplicam a esse leitor de validação. Por exemplo, se o leitor fornecido tiver WhitespaceHandling.None definido, esse leitor de validação também ignorará o espaço em branco.

Quando DTDs (definições de tipo de documento) externas ou esquemas são necessários para validação, a XmlResolver propriedade define o XmlResolver objeto a ser usado para resolver recursos externos.

Confira também

Aplica-se a

XmlValidatingReader(Stream, XmlNodeType, XmlParserContext)

Inicializa uma nova instância da classe XmlValidatingReader com os valores especificados.

public:
 XmlValidatingReader(System::IO::Stream ^ xmlFragment, System::Xml::XmlNodeType fragType, System::Xml::XmlParserContext ^ context);
public XmlValidatingReader (System.IO.Stream xmlFragment, System.Xml.XmlNodeType fragType, System.Xml.XmlParserContext context);
new System.Xml.XmlValidatingReader : System.IO.Stream * System.Xml.XmlNodeType * System.Xml.XmlParserContext -> System.Xml.XmlValidatingReader
Public Sub New (xmlFragment As Stream, fragType As XmlNodeType, context As XmlParserContext)

Parâmetros

xmlFragment
Stream

O fluxo que contém o fragmento XML a ser analisado.

fragType
XmlNodeType

O XmlNodeType do fragmento XML. Isso determina o que o fragmento pode conter (consulte a tabela abaixo).

context
XmlParserContext

O XmlParserContext no qual o fragmento XML deverá ser analisado. Isso inclui o XmlNameTable a ser usado, codificação, o escopo de namespace, xml:lang atual e o escopo xml:space.

Exceções

fragType não é um dos tipos de nó listados na tabela a seguir.

Comentários

Observação

A XmlValidatingReader classe está obsoleta no .NET Framework 2.0. Você pode criar uma instância de validação XmlReader usando a XmlReaderSettings classe e o Create método. Para obter mais informações, consulte a seção de Comentários da página de referência XmlReader.

Esse construtor analisa a cadeia de caracteres fornecida como um fragmento de XML. Se o fragmento XML for um elemento ou atributo, você poderá ignorar as regras de nível raiz para documentos XML bem formados.

A tabela a seguir lista valores válidos e como fragType o leitor analisa cada um dos diferentes tipos de nó.

XmlNodeType Fragmento pode conter
Elemento Qualquer conteúdo de elemento válido (por exemplo, qualquer combinação de elementos, comentários, instruções de processamento, cdata, texto e referências de entidade).
Atributo O valor de um atributo (a parte dentro das aspas).
Documento O conteúdo de um documento XML inteiro; isso impõe regras de nível de documento.

O leitor usa as seguintes etapas para determinar a codificação do fluxo:

  1. Verifica a XmlParserContext.Encoding propriedade para determinar a codificação.

  2. Se a Encoding propriedade for null, o leitor verificará uma marca de ordem de byte no início do fluxo.

  3. Se a Encoding propriedade for null, e nenhuma marca de ordem de byte for encontrada, o leitor assumirá que o fluxo está codificado em UTF-8.

Se esse leitor estiver validando usando dTD (definição de tipo de documento) (ou seja, ValidationType está definido como ValidationType.DTD ou ValidationType.Auto), o XmlParserContext especificado no construtor deve fornecer todas as informações necessárias do DocumentType.

Observação

Não é possível validar um fragmento usando um DTD. Por definição, um DTD requer que um documento inteiro seja carregado para validação.

Se esse leitor estiver validando usando esquemas de XDR (linguagem de definição de esquema XML) ou XDR (redução de XML-Data), use a Schemas propriedade para especificar o XmlSchemaCollection que contém os esquemas (ou seja, XmlParserContext não é necessário fornecer as informações do DocumentType).

Confira também

Aplica-se a

XmlValidatingReader(String, XmlNodeType, XmlParserContext)

Inicializa uma nova instância da classe XmlValidatingReader com os valores especificados.

public:
 XmlValidatingReader(System::String ^ xmlFragment, System::Xml::XmlNodeType fragType, System::Xml::XmlParserContext ^ context);
public XmlValidatingReader (string xmlFragment, System.Xml.XmlNodeType fragType, System.Xml.XmlParserContext context);
new System.Xml.XmlValidatingReader : string * System.Xml.XmlNodeType * System.Xml.XmlParserContext -> System.Xml.XmlValidatingReader
Public Sub New (xmlFragment As String, fragType As XmlNodeType, context As XmlParserContext)

Parâmetros

xmlFragment
String

A cadeia de caracteres que contém o fragmento XML a ser analisado.

fragType
XmlNodeType

O XmlNodeType do fragmento XML. Ele também determina o que a cadeia de caracteres de fragmento pode conter (consulte a tabela abaixo).

context
XmlParserContext

O XmlParserContext no qual o fragmento XML deverá ser analisado. Isso inclui o NameTable a ser usado, codificação, o escopo de namespace, xml:lang atual e o escopo xml:space.

Exceções

fragType não é um dos tipos de nó listados na tabela a seguir.

Exemplos

O exemplo a seguir lê um fragmento XML. Ele usa um XmlParserContext e seu XmlNamespaceManager para manipular a correspondência de namespace.

using System;
using System.IO;
using System.Xml;

public class Sample
{
    public static void Main()
    {
        XmlTextReader reader = null;

        try
        {
            //Create the XML fragment to be parsed.
            string xmlFrag = "<book> " +
                            "<title>Pride And Prejudice</title>" +
                            "<bk:genre>novel</bk:genre>" +
                            "</book>";

            //Create the XmlNamespaceManager that is used to
            //look up namespace information.
            NameTable nt = new NameTable();
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
            nsmgr.AddNamespace("bk", "urn:sample");

            //Create the XmlParserContext.
            XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);

            //Implement the reader.
            reader = new XmlTextReader(xmlFrag, XmlNodeType.Element, context);

            //Parse the XML fragment.  If they exist, display the
            //prefix and namespace URI of each element.
            while (reader.Read())
            {
                if (reader.IsStartElement())
                {
                    if (string.IsNullOrEmpty(reader.Prefix))
                    {
                        Console.WriteLine("<{0}>", reader.LocalName);
                    }
                    else
                    {
                        Console.Write("<{0}:{1}>", reader.Prefix, reader.LocalName);
                        Console.WriteLine(" The namespace URI is " + reader.NamespaceURI);
                    }
                }
            }
        }

        finally
        {
            if (reader != null)
                reader.Close();
        }
    }
} // End class
Imports System.IO
Imports System.Xml

Public Class Sample

    Public Shared Sub Main()
        Dim reader As XmlTextReader = Nothing

        Try
            'Create the XML fragment to be parsed.
            Dim xmlFrag As String = "<book> " & _
                                    "<title>Pride And Prejudice</title>" & _
                                    "<bk:genre>novel</bk:genre>" & _
                                    "</book>"

            'Create the XmlNamespaceManager that is used to
            'look up namespace information.
            Dim nt As New NameTable()
            Dim nsmgr As New XmlNamespaceManager(nt)
            nsmgr.AddNamespace("bk", "urn:sample")

            'Create the XmlParserContext.
            Dim context As New XmlParserContext(Nothing, nsmgr, Nothing, XmlSpace.None)

            'Implement the reader. 
            reader = New XmlTextReader(xmlFrag, XmlNodeType.Element, context)

            'Parse the XML fragment.  If they exist, display the   
            'prefix and namespace URI of each element.
            While reader.Read()
                If reader.IsStartElement() Then
                    If reader.Prefix = String.Empty Then
                        Console.WriteLine("<{0}>", reader.LocalName)
                    Else
                        Console.Write("<{0}:{1}>", reader.Prefix, reader.LocalName)
                        Console.WriteLine(" The namespace URI is " & reader.NamespaceURI)
                    End If
                End If
            End While
        Finally
            If Not (reader Is Nothing) Then
                reader.Close()
            End If
        End Try
    End Sub
End Class

Comentários

Observação

A XmlValidatingReader classe está obsoleta no .NET Framework 2.0. Você pode criar uma instância de validação XmlReader usando a XmlReaderSettings classe e o Create método. Para obter mais informações, consulte a seção de Comentários da página de referência XmlReader.

Esse construtor analisa a cadeia de caracteres fornecida como um fragmento de XML. Se o fragmento XML for um elemento ou atributo, você poderá ignorar as regras de nível raiz para documentos XML bem formados. Esse construtor pode manipular cadeias de caracteres retornadas de ReadInnerXml.

A tabela a seguir lista valores válidos e como fragType o leitor analisa cada um dos diferentes tipos de nó.

XmlNodeType Fragmento pode conter
Elemento Qualquer conteúdo de elemento válido (por exemplo, qualquer combinação de elementos, comentários, instruções de processamento, cdata, texto e referências de entidade).
Atributo O valor de um atributo (a parte dentro das aspas).
Documento O conteúdo de um documento XML inteiro; isso impõe regras de nível de documento.

Se esse leitor for validado usando dtd (definição de tipo de documento) (ou seja, ValidationType está definido como ValidationType.DTD ou ValidationType.Auto), o XmlParserContext especificado no construtor deve fornecer todas as informações necessárias do DocumentType.

Observação

Não é possível validar um fragmento usando DTD. Por definição, o DTD requer que um documento inteiro seja carregado para validação.

Se esse leitor for validado usando esquemas de XDR (linguagem de definição de esquema XML) ou XDR (XML-Data reduzida), use a Schemas propriedade para especificar o XmlSchemaCollection que contém os esquemas (não XmlParserContext é necessário fornecer as informações do DocumentType).

Confira também

Aplica-se a