Freigeben über


Überprüfen eines XML-Dokuments im DOM

DieXmlDocument Klasse überprüft den XML-Code im Document Object Model (DOM) nicht standardmäßig anhand eines XML-Schemadefinitionsschemas (XSD) oder einer Dokumenttypdefinition (Document Type Definition, DTD). Der XML-Code wird nur als wohlgeformt überprüft.

Um den XML-Code im DOM zu überprüfen, können Sie den XML-Code so überprüfen, wie er in das DOM geladen wird, indem Sie eine Schemaüberprüfung XmlReader an die Load Methode der XmlDocument Klasse übergeben oder ein zuvor nicht überprüftes XML-Dokument im DOM mithilfe Validate der Methode der XmlDocument Klasse überprüfen.

Überprüfen eines XML-Dokuments während des Ladens in das DOM

Die XmlDocument-Klasse validiert die XML-Daten, während sie in das DOM geladen werden, wenn ein Validator XmlReader an die Load-Methode der XmlDocument-Klasse übergeben wird.

Nach erfolgreicher Überprüfung werden Schemastandardwerte angewendet, Textwerte werden nach Bedarf in atome Werte konvertiert, und Typinformationen werden überprüften Informationselementen zugeordnet. Daher werden typisierte XML-Daten durch zuvor nicht typisierte XML-Daten ersetzt.

XML-Schema-Validating-XmlReader erstellen

Führen Sie die folgenden Schritte aus, um einen XML-Schema-Validator XmlReader zu erstellen.

  1. Erstellen Sie eine neue XmlReaderSettings Instanz.

  2. Fügen Sie der Schemas Eigenschaft der XmlReaderSettings Instanz ein XML-Schema hinzu.

  3. Geben Sie Schema als ValidationType an.

  4. Geben Sie optional ValidationFlags und ValidationEventHandler zur Behandlung von Schema-Validierungsfehlern und Warnungen an, die während der Überprüfung aufgetreten sind.

  5. Übergeben Sie schließlich das XmlReaderSettings Objekt an die Create Methode der XmlReader Klasse zusammen mit dem XML-Dokument, wodurch eine Schemaüberprüfung erstellt wird XmlReader.

Beispiel

Im folgenden Codebeispiel überprüft eine Schemaüberprüfung XmlReader die xml-Daten, die in das DOM geladen wurden. Ungültige Änderungen werden an dem XML-Dokument vorgenommen, und das Dokument wird dann erneut überprüft, was zu Schemaüberprüfungsfehlern führt. Schließlich wird einer der Fehler korrigiert, und dann wird ein Teil des XML-Dokuments teilweise überprüft.

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

class XmlDocumentValidationExample
{
    static void Main(string[] args)
    {
        try
        {
            // Create a schema validating XmlReader.
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd");
            settings.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler);
            settings.ValidationFlags = settings.ValidationFlags | XmlSchemaValidationFlags.ReportValidationWarnings;
            settings.ValidationType = ValidationType.Schema;

            XmlReader reader = XmlReader.Create("contosoBooks.xml", settings);

            // The XmlDocument validates the XML document contained
            // in the XmlReader as it is loaded into the DOM.
            XmlDocument document = new XmlDocument();
            document.Load(reader);

            // Make an invalid change to the first and last
            // price elements in the XML document, and write
            // the XmlSchemaInfo values assigned to the price
            // element during load validation to the console.
            XmlNamespaceManager manager = new XmlNamespaceManager(document.NameTable);
            manager.AddNamespace("bk", "http://www.contoso.com/books");

            XmlNode priceNode = document.SelectSingleNode(@"/bk:bookstore/bk:book/bk:price", manager);

            Console.WriteLine($"SchemaInfo.IsDefault: {priceNode.SchemaInfo.IsDefault}");
            Console.WriteLine($"SchemaInfo.IsNil: {priceNode.SchemaInfo.IsNil}");
            Console.WriteLine($"SchemaInfo.SchemaElement: {priceNode.SchemaInfo.SchemaElement}");
            Console.WriteLine($"SchemaInfo.SchemaType: {priceNode.SchemaInfo.SchemaType}");
            Console.WriteLine($"SchemaInfo.Validity: {priceNode.SchemaInfo.Validity}");

            priceNode.InnerXml = "A";

            XmlNodeList priceNodes = document.SelectNodes(@"/bk:bookstore/bk:book/bk:price", manager);
            XmlNode lastprice = priceNodes[priceNodes.Count - 1];

            lastprice.InnerXml = "B";

            // Validate the XML document with the invalid changes.
            // The invalid changes cause schema validation errors.
            document.Validate(ValidationEventHandler);

            // Correct the invalid change to the first price element.
            priceNode.InnerXml = "8.99";

            // Validate only the first book element. The last book
            // element is invalid, but not included in validation.
            XmlNode bookNode = document.SelectSingleNode(@"/bk:bookstore/bk:book", manager);
            document.Validate(ValidationEventHandler, bookNode);
        }
        catch (XmlException ex)
        {
            Console.WriteLine($"XmlDocumentValidationExample.XmlException: {ex.Message}");
        }
        catch(XmlSchemaValidationException ex)
        {
            Console.WriteLine($"XmlDocumentValidationExample.XmlSchemaValidationException: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"XmlDocumentValidationExample.Exception: {ex.Message}");
        }
    }

    static void ValidationEventHandler(object sender, System.Xml.Schema.ValidationEventArgs args)
    {
        if (args.Severity == XmlSeverityType.Warning)
            Console.Write("\nWARNING: ");
        else if (args.Severity == XmlSeverityType.Error)
            Console.Write("\nERROR: ");

        Console.WriteLine(args.Message);
    }
}
Imports System.Xml
Imports System.Xml.Schema

Class XmlDocumentValidationExample

    Shared Sub Main()

        Try

            ' Create a schema validating XmlReader.
            Dim settings As XmlReaderSettings = New XmlReaderSettings()
            settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd")
            AddHandler settings.ValidationEventHandler, New ValidationEventHandler(AddressOf ValidationEventHandler)
            settings.ValidationFlags = settings.ValidationFlags And XmlSchemaValidationFlags.ReportValidationWarnings
            settings.ValidationType = ValidationType.Schema

            Dim reader As XmlReader = XmlReader.Create("contosoBooks.xml", settings)

            ' The XmlDocument validates the XML document contained
            ' in the XmlReader as it is loaded into the DOM.
            Dim document As XmlDocument = New XmlDocument()
            document.Load(reader)

            ' Make an invalid change to the first and last 
            ' price elements in the XML document, and write
            ' the XmlSchemaInfo values assigned to the price
            ' element during load validation to the console.
            Dim manager As XmlNamespaceManager = New XmlNamespaceManager(document.NameTable)
            manager.AddNamespace("bk", "http://www.contoso.com/books")

            Dim priceNode As XmlNode = document.SelectSingleNode("/bk:bookstore/bk:book/bk:price", manager)

            Console.WriteLine("SchemaInfo.IsDefault: {0}", priceNode.SchemaInfo.IsDefault)
            Console.WriteLine("SchemaInfo.IsNil: {0}", priceNode.SchemaInfo.IsNil)
            Console.WriteLine("SchemaInfo.SchemaElement: {0}", priceNode.SchemaInfo.SchemaElement)
            Console.WriteLine("SchemaInfo.SchemaType: {0}", priceNode.SchemaInfo.SchemaType)
            Console.WriteLine("SchemaInfo.Validity: {0}", priceNode.SchemaInfo.Validity)

            priceNode.InnerXml = "A"

            Dim priceNodes As XmlNodeList = document.SelectNodes("/bk:bookstore/bk:book/bk:price", manager)
            Dim lastprice As XmlNode = priceNodes(priceNodes.Count - 1)

            lastprice.InnerXml = "B"

            ' Validate the XML document with the invalid changes.
            ' The invalid changes cause schema validation errors.
            document.Validate(AddressOf ValidationEventHandler)

            ' Correct the invalid change to the first price element.
            priceNode.InnerXml = "8.99"

            ' Validate only the first book element. The last book
            ' element is invalid, but not included in validation.
            Dim bookNode As XmlNode = document.SelectSingleNode("/bk:bookstore/bk:book", manager)
            document.Validate(AddressOf ValidationEventHandler, bookNode)

        Catch ex As XmlException
            Console.WriteLine("XmlDocumentValidationExample.XmlException: {0}", ex.Message)

        Catch ex As XmlSchemaValidationException
            Console.WriteLine("XmlDocumentValidationExample.XmlSchemaValidationException: {0}", ex.Message)

        Catch ex As Exception
            Console.WriteLine("XmlDocumentValidationExample.Exception: {0}", ex.Message)

        End Try

    End Sub

    Shared Sub ValidationEventHandler(ByVal sender As Object, ByVal args As ValidationEventArgs)

        If args.Severity = XmlSeverityType.Warning Then
            Console.Write(vbCrLf & "WARNING: ")
        Else
            If args.Severity = XmlSeverityType.Error Then
                Console.Write(vbCrLf & "ERROR: ")
            End If
        End If
        Console.WriteLine(args.Message)

    End Sub

End Class

Im Beispiel wird die contosoBooks.xml Datei als Eingabe verwendet.

<?xml version="1.0" encoding="utf-8" ?>
<bookstore xmlns="http://www.contoso.com/books">
    <book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0">
        <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" publicationdate="1967-11-17" ISBN="0-201-63361-2">
        <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" publicationdate="1991-02-15" ISBN="1-861001-57-6">
        <title>The Gorgias</title>
        <author>
            <name>Plato</name>
        </author>
        <price>9.99</price>
    </book>
</bookstore>

Im Beispiel wird die contosoBooks.xsd Datei auch als Eingabe verwendet.

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://www.contoso.com/books" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="bookstore">
        <xs:complexType>
            <xs:sequence>
                <xs:element maxOccurs="unbounded" name="book">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="title" type="xs:string" />
                            <xs:element name="author">
                                <xs:complexType>
                                    <xs:sequence>
                                        <xs:element minOccurs="0" name="name" type="xs:string" />
                                        <xs:element minOccurs="0" name="first-name" type="xs:string" />
                                        <xs:element minOccurs="0" name="last-name" type="xs:string" />
                                    </xs:sequence>
                                </xs:complexType>
                            </xs:element>
                            <xs:element name="price" type="xs:decimal" />
                        </xs:sequence>
                        <xs:attribute name="genre" type="xs:string" use="required" />
                        <xs:attribute name="publicationdate" type="xs:date" use="required" />
                        <xs:attribute name="ISBN" type="xs:string" use="required" />
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

Beachten Sie beim Überprüfen von XML-Daten folgendes, wenn sie in das DOM geladen wird.

  • Im obigen Beispiel wird ValidationEventHandler jedes Mal aufgerufen, wenn ein ungültiger Typ auftritt. Wenn ein Wert ValidationEventHandler für die Überprüfung XmlReader nicht festgelegt ist, wird ein XmlSchemaValidationException ausgelöst, wenn Load ein Attribut oder Elementtyp nicht mit dem im validierenden Schema angegebenen Typ übereinstimmt.

  • Wenn ein XML-Dokument in ein Objekt geladen wird, das ein XmlDocument zugeordnetes Schema mit Standardwerten enthält, behandelt XmlDocument diese Standardwerte, als ob sie im XML-Dokument selbst erschienen wären. Dies bedeutet, dass die Eigenschaft IsEmptyElement immer false für ein Element zurückgibt, das standardmäßig aus dem Schema stammt. Auch wenn es im XML-Dokument als leeres Element geschrieben wurde.

Überprüfen eines XML-Dokuments im DOM

Die Validate-Methode der XmlDocument-Klasse validiert die im DOM geladenen XML-Daten anhand der Schemas, die sich in der XmlDocument-Eigenschaft des Schemas-Objekts befinden. Nach erfolgreicher Überprüfung werden Schemastandardwerte angewendet, Textwerte werden nach Bedarf in atome Werte konvertiert, und Typinformationen werden überprüften Informationselementen zugeordnet. Daher werden typisierte XML-Daten durch zuvor nicht typisierte XML-Daten ersetzt.

Das folgende Beispiel ähnelt dem Beispiel in "Validating an XML Document As It Is Loaded into the DOM" above. In diesem Beispiel wird das XML-Dokument nicht überprüft, da es in das DOM geladen wird, sondern stattdessen überprüft wird, nachdem es mithilfe Validate der Methode der XmlDocument Klasse in das DOM geladen wurde. Die Validate-Methode überprüft das XML-Dokument anhand der XML-Schemas, die in der Schemas-Eigenschaft der XmlDocument enthalten sind. Anschließend werden ungültige Änderungen an dem XML-Dokument vorgenommen, und das Dokument wird dann neuvalidiert, was zu Schemaüberprüfungsfehlern führt. Schließlich wird einer der Fehler korrigiert, und dann wird ein Teil des XML-Dokuments teilweise überprüft.

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

class XmlDocumentValidationExample
{
    static void Main(string[] args)
    {
        try
        {
            // Create a new XmlDocument instance and load
            // the XML document into the DOM.
            XmlDocument document = new XmlDocument();
            document.Load("contosoBooks.xml");

            // Add the XML schema for the XML document to the
            // Schemas property of the XmlDocument.
            document.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd");

            // Validate the XML document loaded into the DOM.
            document.Validate(ValidationEventHandler);

            // Make an invalid change to the first and last
            // price elements in the XML document, and write
            // the XmlSchemaInfo values assigned to the price
            // element during validation to the console.
            XmlNamespaceManager manager = new XmlNamespaceManager(document.NameTable);
            manager.AddNamespace("bk", "http://www.contoso.com/books");

            XmlNode priceNode = document.SelectSingleNode(@"/bk:bookstore/bk:book/bk:price", manager);

            Console.WriteLine($"SchemaInfo.IsDefault: {priceNode.SchemaInfo.IsDefault}");
            Console.WriteLine($"SchemaInfo.IsNil: {priceNode.SchemaInfo.IsNil}");
            Console.WriteLine($"SchemaInfo.SchemaElement: {priceNode.SchemaInfo.SchemaElement}");
            Console.WriteLine($"SchemaInfo.SchemaType: {priceNode.SchemaInfo.SchemaType}");
            Console.WriteLine($"SchemaInfo.Validity: {priceNode.SchemaInfo.Validity}");

            priceNode.InnerXml = "A";

            XmlNodeList priceNodes = document.SelectNodes(@"/bk:bookstore/bk:book/bk:price", manager);
            XmlNode lastprice = priceNodes[priceNodes.Count - 1];

            lastprice.InnerXml = "B";

            // Validate the XML document with the invalid changes.
            // The invalid changes cause schema validation errors.
            document.Validate(ValidationEventHandler);

            // Correct the invalid change to the first price element.
            priceNode.InnerXml = "8.99";

            // Validate only the first book element. The last book
            // element is invalid, but not included in validation.
            XmlNode bookNode = document.SelectSingleNode(@"/bk:bookstore/bk:book", manager);
            document.Validate(ValidationEventHandler, bookNode);
        }
        catch (XmlException ex)
        {
            Console.WriteLine($"XmlDocumentValidationExample.XmlException: {ex.Message}");
        }
        catch(XmlSchemaValidationException ex)
        {
            Console.WriteLine($"XmlDocumentValidationExample.XmlSchemaValidationException: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"XmlDocumentValidationExample.Exception: {ex.Message}");
        }
    }

    static void ValidationEventHandler(object sender, System.Xml.Schema.ValidationEventArgs args)
    {
        if (args.Severity == XmlSeverityType.Warning)
            Console.Write("\nWARNING: ");
        else if (args.Severity == XmlSeverityType.Error)
            Console.Write("\nERROR: ");

        Console.WriteLine(args.Message);
    }
}
Imports System.Xml
Imports System.Xml.Schema

Class XmlDocumentValidationExample

    Shared Sub Main()

        Try

            ' Create a new XmlDocument instance and load
            ' the XML document into the DOM.
            Dim document As XmlDocument = New XmlDocument()
            document.Load("contosoBooks.xml")

            ' Add the XML schema for the XML document to the
            ' Schemas property of the XmlDocument.
            document.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd")

            ' Validate the XML document loaded into the DOM.
            document.Validate(AddressOf ValidationEventHandler)

            ' Make an invalid change to the first and last 
            ' price elements in the XML document, and write
            ' the XmlSchemaInfo values assigned to the price
            ' element during validation to the console.
            Dim manager As XmlNamespaceManager = New XmlNamespaceManager(document.NameTable)
            manager.AddNamespace("bk", "http://www.contoso.com/books")

            Dim priceNode As XmlNode = document.SelectSingleNode("/bk:bookstore/bk:book/bk:price", manager)

            Console.WriteLine("SchemaInfo.IsDefault: {0}", priceNode.SchemaInfo.IsDefault)
            Console.WriteLine("SchemaInfo.IsNil: {0}", priceNode.SchemaInfo.IsNil)
            Console.WriteLine("SchemaInfo.SchemaElement: {0}", priceNode.SchemaInfo.SchemaElement)
            Console.WriteLine("SchemaInfo.SchemaType: {0}", priceNode.SchemaInfo.SchemaType)
            Console.WriteLine("SchemaInfo.Validity: {0}", priceNode.SchemaInfo.Validity)

            priceNode.InnerXml = "A"

            Dim priceNodes As XmlNodeList = document.SelectNodes("/bk:bookstore/bk:book/bk:price", manager)
            Dim lastprice As XmlNode = priceNodes(priceNodes.Count - 1)

            lastprice.InnerXml = "B"

            ' Validate the XML document with the invalid changes.
            ' The invalid changes cause schema validation errors.
            document.Validate(AddressOf ValidationEventHandler)

            ' Correct the invalid change to the first price element.
            priceNode.InnerXml = "8.99"

            ' Validate only the first book element. The last book
            ' element is invalid, but not included in validation.
            Dim bookNode As XmlNode = document.SelectSingleNode("/bk:bookstore/bk:book", manager)
            document.Validate(AddressOf ValidationEventHandler, bookNode)

        Catch ex As XmlException
            Console.WriteLine("XmlDocumentValidationExample.XmlException: {0}", ex.Message)

        Catch ex As XmlSchemaValidationException
            Console.WriteLine("XmlDocumentValidationExample.XmlSchemaValidationException: {0}", ex.Message)

        Catch ex As Exception
            Console.WriteLine("XmlDocumentValidationExample.Exception: {0}", ex.Message)

        End Try

    End Sub

    Shared Sub ValidationEventHandler(ByVal sender As Object, ByVal args As ValidationEventArgs)

        If args.Severity = XmlSeverityType.Warning Then
            Console.Write(vbCrLf & "WARNING: ")
        Else
            If args.Severity = XmlSeverityType.Error Then
                Console.Write(vbCrLf & "ERROR: ")
            End If
        End If
        Console.WriteLine(args.Message)

    End Sub

End Class

Im Beispiel werden die Dateien contosoBooks.xml und contosoBooks.xsd, die in "Validieren eines XML-Dokuments beim Laden in das DOM" oben genannt werden, als Eingaben verwendet.

Behandeln von Überprüfungsfehlern und Warnungen

XML-Schemaüberprüfungsfehler werden beim Überprüfen von XML-Daten gemeldet, die im DOM geladen wurden. Sie werden über alle Schemaüberprüfungsfehler informiert, die beim Überprüfen der XML-Daten beim Laden gefunden wurden, oder beim Überprüfen eines zuvor nicht überprüften XML-Dokuments.

Validierungsfehler werden von der ValidationEventHandler behandelt. Wenn eine ValidationEventHandler der XmlReaderSettings-Instanz zugewiesen oder an die Validate-Methode der XmlDocument-Klasse übergeben wurde, wird ValidationEventHandler die Behandlung der Schemaüberprüfungsfehler durchgeführt. Andernfalls wird ein XmlSchemaValidationException ausgelöst, wenn ein Schemaüberprüfungsfehler auftritt.

Hinweis

Die XML-Daten werden trotz Schemaüberprüfungsfehlern in das DOM geladen, es sei denn, Ihr ValidationEventHandler löst eine Ausnahme aus, um den Prozess zu beenden.

Schemaüberprüfungswarnungen werden nur gemeldet, wenn die Flagge ReportValidationWarnings für das Objekt XmlReaderSettings angegeben ist.

Beispiele, die das ValidationEventHandler veranschaulichen, finden Sie oben unter "Validieren eines XML-Dokuments beim Laden in den DOM" und "Validieren eines XML-Dokuments im DOM".

Siehe auch