Compartir a través de


Validación con un objeto XmlReader contenido

Actualización: November 2007

Puede crear un objeto XmlReader nuevo que esté contenido en otro objeto XmlReader. Esto le permite agregar características adicionales a otro objeto XmlReader. Por ejemplo, la clase XmlNodeReader no es compatible con la validación de datos. Al crear un objeto XmlReader que contenga el objeto XmlNodeReader, puede validar los datos almacenados en el objeto XmlNodeReader.

Ejemplo

En el siguiente ejemplo se carga y se modifica un archivo XML en un documento XML. El documento XML se pasa a un XmlNodeReader, que luego se pasa al método XmlReader.Create. Cuando el sistema de lectura de validación analiza el archivo, puede validar cualquier cambio realizado en el archivo XML.

Imports System
Imports System.Xml
Imports System.Xml.Schema
Imports System.IO

public class Sample 

  public shared sub Main() 

    ' Create and load the XML document.
    Dim doc as XmlDocument = new XmlDocument()
    doc.Load("booksSchema.xml")

    ' Make changes to the document.
    Dim book as XmlElement
    book = CType(doc.DocumentElement.FirstChild, XmlElement)
    book.SetAttribute("publisher", "Worldwide Publishing")

    ' Create an XmlNodeReader using the XML document.
    Dim nodeReader as XmlNodeReader = new XmlNodeReader(doc)

    ' Set the validation settings on the XmlReaderSettings object.
    Dim settings as XmlReaderSettings = new XmlReaderSettings()
    settings.ValidationType = ValidationType.Schema
    settings.Schemas.Add("urn:bookstore-schema", "books.xsd")
    AddHandler settings.ValidationEventHandler, AddressOf ValidationCallBack

    ' Create a validating reader that wraps the XmlNodeReader object.
    Dim reader as XmlReader = XmlReader.Create(nodeReader,settings)

    ' Parse the XML file.
    while (reader.Read())
    end while
  end sub

  ' Display any validation errors.
  private shared sub ValidationCallBack(sender as object, e as ValidationEventArgs)
    Console.WriteLine("Validation Error: {0}", e.Message)
  end sub

end class
using System;
using System.Xml;
using System.Xml.Schema;
using System.IO;

public class Sample {

  public static void Main() {

    // Create and load the XML document.
    XmlDocument doc = new XmlDocument();
    doc.Load("booksSchema.xml");

    // Make changes to the document.
    XmlElement book = (XmlElement) doc.DocumentElement.FirstChild;
    book.SetAttribute("publisher", "Worldwide Publishing");

    // Create an XmlNodeReader using the XML document.
    XmlNodeReader nodeReader = new XmlNodeReader(doc);

    // Set the validation settings on the XmlReaderSettings object.
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.ValidationType = ValidationType.Schema;
    settings.Schemas.Add("urn:bookstore-schema", "books.xsd");
    settings.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);

   // Create a validating reader that wraps the XmlNodeReader object.
   XmlReader reader = XmlReader.Create(nodeReader, settings);

   // Parse the XML file.
   while (reader.Read());
  }

  // Display any validation errors.
  private static void ValidationCallBack(object sender, ValidationEventArgs e) {
    Console.WriteLine("Validation Error: {0}", e.Message);
  }
}

Entrada

Los siguientes archivos se utilizan como entrada.

bookSchema.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>

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>

Resultados

Error de validación: No se ha declarado el atributo 'publisher'.

Vea también

Conceptos

Leer fragmentos de XML con XmlReader

Otros recursos

Validación de datos XML con XmlReader