Condividi tramite


Convalida utilizzando un oggetto XmlReader incapsulato

È possibile creare un nuovo oggetto XmlReader disposto intorno all'oggetto XmlReader. Ciò consente di aggiungere ulteriori funzionalità a un altro oggetto XmlReader. Ad esempio, la classe XmlNodeReader non supporta la convalida dei dati. Creando un oggetto XmlReader disposto intorno all'oggetto XmlNodeReader, è possibile convalidare i dati archiviati nell'oggettoXmlNodeReader.

Esempio

Nell'esempio seguente un file XML viene caricato in un documento XML e modificato. Il documento XML viene passato a un tipo XmlNodeReader, che a sua volta viene passato al metodoXmlReader.Create. Quando analizza il file, il lettore di convalida è in grado di convalidare qualsiasi modifica apportata la file 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);
  }
}

Input

Vengono utilizzati come input i seguenti file.

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>

Output

Errore di convalida: l'attributo 'publisher' non è dichiarato.

Vedere anche

Concetti

Lettura di XML con XmlReader

Altre risorse

Convalida di dati XML con XmlReader