Een XML-document valideren in de DOM
DeXmlDocument klasse valideert de XML in het Document Object Model (DOM) niet op basis van een XSD-schema (XSD) schema of documenttypedefinitie (DTD). De XML is alleen goed opgemaakt.
Als u de XML in de DOM wilt valideren, kunt u de XML valideren terwijl deze in de DOM wordt geladen door een schemavalidatie XmlReader door te geven aan de Load methode van de XmlDocument klasse of een eerder niet-gevalideerd XML-document in de DOM valideren met behulp van de Validate methode van de XmlDocument klasse.
Een XML-document valideren terwijl het wordt geladen in de DOM
De XmlDocument klasse valideert de XML-gegevens terwijl deze in de DOM worden geladen wanneer een validatie XmlReader wordt doorgegeven aan de Load methode van de XmlDocument klasse.
Na een geslaagde validatie worden schemastandaarden toegepast, worden tekstwaarden indien nodig geconverteerd naar atomische waarden en worden typegegevens gekoppeld aan gevalideerde informatie-items. Als gevolg hiervan vervangt getypte XML-gegevens eerder niet-getypte XML-gegevens.
Een XML-schema validerende XmlReader maken
Volg deze stappen om een XML-schemavalidatie XmlReaderte maken.
Een nieuw XmlReaderSettings exemplaar maken.
Voeg een XML-schema toe aan de Schemas eigenschap van het XmlReaderSettings exemplaar.
Geef
Schema
op als de ValidationType.Geef desgewenst ValidationFlags op en een ValidationEventHandler om schemavalidatiefouten en waarschuwingen tijdens de validatie af te handelen.
Geef tot slot het XmlReaderSettings object door aan de Create methode van de XmlReader klasse, samen met het XML-document, waardoor een schemavalidatie XmlReaderwordt gemaakt.
Opmerking
In het volgende codevoorbeeld valideert een schemavalidatie XmlReader de XML-gegevens die in de DOM zijn geladen. Er worden ongeldige wijzigingen aangebracht in het XML-document en het document wordt vervolgens opnieuw gevalideerd, waardoor schemavalidatiefouten ontstaan. Ten slotte wordt een van de fouten gecorrigeerd en wordt een deel van het XML-document gedeeltelijk gevalideerd.
#using <System.Xml.dll>
using namespace System;
using namespace System::Xml;
using namespace System::Xml::Schema;
ref class XmlDocumentValidationExample
{
public:
static void Main()
{
try
{
// Create a schema validating XmlReader.
XmlReaderSettings^ settings = gcnew XmlReaderSettings();
settings->Schemas->Add("http://www.contoso.com/books", "contosoBooks.xsd");
ValidationEventHandler^ eventHandler = gcnew ValidationEventHandler(ValidationEventHandlerOne);
settings->ValidationEventHandler += eventHandler;
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 = gcnew 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 = gcnew 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: {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";
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(eventHandler);
// 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(eventHandler, bookNode);
}
catch (XmlException^ ex)
{
Console::WriteLine("XmlDocumentValidationExample.XmlException: {0}", ex->Message);
}
catch(XmlSchemaValidationException^ ex)
{
Console::WriteLine("XmlDocumentValidationExample.XmlSchemaValidationException: {0}", ex->Message);
}
catch (Exception^ ex)
{
Console::WriteLine("XmlDocumentValidationExample.Exception: {0}", ex->Message);
}
}
static void ValidationEventHandlerOne(Object^ sender, ValidationEventArgs^ args)
{
if (args->Severity == XmlSeverityType::Warning)
Console::Write("\nWARNING: ");
else if (args->Severity == XmlSeverityType::Error)
Console::Write("\nERROR: ");
Console::WriteLine(args->Message);
}
};
int main()
{
XmlDocumentValidationExample::Main();
return 0;
}
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: {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";
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: {0}", ex.Message);
}
catch(XmlSchemaValidationException ex)
{
Console.WriteLine("XmlDocumentValidationExample.XmlSchemaValidationException: {0}", ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("XmlDocumentValidationExample.Exception: {0}", 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
In het voorbeeld wordt het contosoBooks.xml
bestand als invoer gebruikt.
<?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>
In het voorbeeld wordt het contosoBooks.xsd
bestand ook als invoer gebruikt.
<?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>
Houd rekening met het volgende bij het valideren van XML-gegevens terwijl deze in de DOM worden geladen.
In het bovenstaande voorbeeld wordt de ValidationEventHandler aangeroepen wanneer er een ongeldig type wordt aangetroffen. Als een ValidationEventHandler waarde niet is ingesteld op het valideren XmlReader, wordt er een XmlSchemaValidationException gegenereerd wanneer Load wordt aangeroepen als een kenmerk of elementtype niet overeenkomt met het overeenkomstige type dat is opgegeven in het validatieschema.
Wanneer een XML-document wordt geladen in een XmlDocument object met een gekoppeld schema dat standaardwaarden definieert, XmlDocument worden deze standaardwaarden behandeld alsof ze in het XML-document worden weergegeven. Dit betekent dat de IsEmptyElement eigenschap altijd wordt geretourneerd
false
voor een element dat standaard is ingesteld vanuit het schema. Zelfs als het in het XML-document is geschreven als een leeg element.
Een XML-document valideren in de DOM
De Validate methode van de XmlDocument klasse valideert de XML-gegevens die in de DOM zijn geladen op basis van de schema's in de eigenschap van Schemas het XmlDocument object. Na een geslaagde validatie worden schemastandaarden toegepast, worden tekstwaarden indien nodig geconverteerd naar atomische waarden en worden typegegevens gekoppeld aan gevalideerde informatie-items. Als gevolg hiervan vervangt getypte XML-gegevens eerder niet-getypte XML-gegevens.
Het onderstaande voorbeeld is vergelijkbaar met het voorbeeld in 'Validating an XML Document As It Is Loaded into the DOM' hierboven. In dit voorbeeld wordt het XML-document niet gevalideerd omdat het in de DOM wordt geladen, maar wordt gevalideerd nadat het in de DOM is geladen met behulp van de Validate methode van de XmlDocument klasse. De Validate methode valideert het XML-document op basis van de XML-schema's in de Schemas eigenschap van de XmlDocument. Er worden vervolgens ongeldige wijzigingen aangebracht in het XML-document en het document wordt vervolgens opnieuw gevalideerd, waardoor schemavalidatiefouten optreden. Ten slotte wordt een van de fouten gecorrigeerd en wordt een deel van het XML-document gedeeltelijk gevalideerd.
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: {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";
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: {0}", ex.Message);
}
catch(XmlSchemaValidationException ex)
{
Console.WriteLine("XmlDocumentValidationExample.XmlSchemaValidationException: {0}", ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("XmlDocumentValidationExample.Exception: {0}", 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
In het voorbeeld wordt de invoer gebruikt van de contosoBooks.xml
bestanden contosoBooks.xsd
waarnaar wordt verwezen in 'Een XML-document valideren zoals het is geladen in de DOM' hierboven.
Validatiefouten en waarschuwingen afhandelen
Xml-schemavalidatiefouten worden gerapporteerd bij het valideren van XML-gegevens die in de DOM zijn geladen. U ontvangt een melding over alle schemavalidatiefouten die zijn gevonden tijdens het valideren van de XML-gegevens terwijl deze worden geladen of bij het valideren van een eerder niet-gevalideerd XML-document.
Validatiefouten worden verwerkt door de ValidationEventHandler. Als een ValidationEventHandler is toegewezen aan het XmlReaderSettings exemplaar of is doorgegeven aan de Validate methode van de XmlDocument klasse, ValidationEventHandler worden schemavalidatiefouten verwerkt. Anders wordt er een XmlSchemaValidationException gegenereerd wanneer er een schemavalidatiefout optreedt.
Notitie
De XML-gegevens worden geladen in de DOM ondanks schemavalidatiefouten, tenzij u ValidationEventHandler een uitzondering genereert om het proces te stoppen.
Schemavalidatiewaarschuwingen worden niet gerapporteerd, tenzij de ReportValidationWarnings vlag is opgegeven voor het XmlReaderSettings object.
Zie 'Validating an XML Document As It Is Loaded into the DOM' (Een XML-document valideren in de DOM) en 'Een XML-document valideren in de DOM' hierboven voor voorbeelden ValidationEventHandler.