Nuta
Dostęp do tej strony wymaga autoryzacji. Możesz spróbować zalogować się lub zmienić katalogi.
Dostęp do tej strony wymaga autoryzacji. Możesz spróbować zmienić katalogi.
KlasaXmlDocument nie weryfikuje kodu XML w modelu obiektów dokumentów (DOM) względem schematu języka definicji schematu XML (XSD) ani definicji typu dokumentu (DTD) domyślnie; kod XML jest weryfikowany tylko pod kątem prawidłowo sformułowanego.
pl-PL: Aby zweryfikować kod XML w modelu DOM, możesz zweryfikować kod XML, gdy jest ładowany do modelu DOM, przekazując XmlReader schematu do metody Load klasy XmlDocument, lub walidować wcześniej niewalidowany dokument XML w modelu DOM przy użyciu metody Validate klasy XmlDocument.
Weryfikowanie dokumentu XML podczas ładowania do modelu DOM
Klasa XmlDocument weryfikuje dane XML podczas ich ładowania do modelu DOM, gdy obiekt walidatora XmlReader jest przekazywany do metody Load klasy XmlDocument.
Po pomyślnej weryfikacji są stosowane wartości domyślne schematu, wartości tekstowe są konwertowane na wartości niepodzielne w razie potrzeby, a informacje o typie są skojarzone z zweryfikowanymi elementami informacji. W rezultacie typizowane dane XML zastępują wcześniej nietypizowane dane XML.
Tworzenie obiektu XmlReader dla XML Schema-Validating
Aby utworzyć XmlReader walidujący zgodność z schematem XML, wykonaj następujące kroki.
Utwórz nową instancję XmlReaderSettings.
Dodaj schemat XML do Schemas właściwości XmlReaderSettings wystąpienia.
Określ
Schemajako .ValidationTypeOpcjonalnie określ ValidationFlags i ValidationEventHandler do obsługi błędów i ostrzeżeń napotkanych podczas walidacji schematu.
Na koniec przekaż XmlReaderSettings obiekt do metody Create klasy XmlReader wraz z dokumentem XML, tworząc obiekt walidujący schemat XmlReader.
Przykład
W poniższym przykładzie kodu, moduł weryfikujący zgodność ze schematem weryfikuje dane XML załadowane do modelu DOM. Nieprawidłowe modyfikacje są wprowadzane do dokumentu XML, a dokument jest następnie zmieniany ponownie, powodując błędy walidacji schematu. Na koniec jeden z błędów jest poprawiany, a następnie część dokumentu XML jest częściowo weryfikowana.
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
W przykładzie plik contosoBooks.xml jest pobierany jako dane wejściowe.
<?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>
W przykładzie jako dane wejściowe pobierany jest również plik contosoBooks.xsd.
<?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>
Podczas sprawdzania poprawności danych XML podczas ładowania ich do modelu DOM należy wziąć pod uwagę następujące kwestie.
W powyższym przykładzie, ValidationEventHandler jest wywoływane za każdym razem, gdy wystąpi nieprawidłowy typ. Jeśli ValidationEventHandler nie jest ustawiony na walidującym XmlReader, XmlSchemaValidationException jest zwracany, gdy Load jest wywoływane, jeśli jakikolwiek atrybut lub typ elementu nie pasuje do odpowiedniego typu określonego w schemacie walidacyjnym.
Gdy dokument XML jest ładowany do XmlDocument obiektu ze skojarzonym schematem, który definiuje wartości domyślne, XmlDocument te wartości domyślne są traktowane tak, jakby były wyświetlane w dokumencie XML. Oznacza to, że właściwość IsEmptyElement zawsze zwraca
falsedla elementu, który został ustawiony domyślnie ze schematu. Nawet jeśli w dokumencie XML został zapisany jako pusty element.
Weryfikowanie dokumentu XML w modelu DOM
Metoda Validate klasy XmlDocument weryfikuje dane XML załadowane w modelu DOM względem schematów właściwości XmlDocument obiektu Schemas. Po pomyślnej weryfikacji są stosowane wartości domyślne schematu, wartości tekstowe są konwertowane na wartości niepodzielne w razie potrzeby, a informacje o typie są skojarzone z zweryfikowanymi elementami informacji. W rezultacie typizowane dane XML zastępują wcześniej nietypizowane dane XML.
Poniższy przykład jest podobny do przykładu opisanego wcześniej w "Weryfikowanie dokumentu XML podczas ładowania do DOM". W tym przykładzie dokument XML nie jest weryfikowany podczas ładowania do modelu DOM, ale jest weryfikowany po załadowaniu do modelu DOM, przy użyciu metody Validate klasy XmlDocument. Metoda Validate weryfikuje dokument XML względem schematów XML zawartych we Schemas właściwości XmlDocument. Nieprawidłowe modyfikacje są następnie wprowadzane do dokumentu XML, a dokument jest następnie zmieniany ponownie, powodując błędy weryfikacji schematu. Na koniec jeden z błędów jest poprawiany, a następnie część dokumentu XML jest częściowo weryfikowana.
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
Przykład przyjmuje jako dane wejściowe pliki contosoBooks.xml i contosoBooks.xsd, o których mowa w sekcji "Weryfikowanie dokumentu XML podczas jego ładowania do modelu DOM" powyżej.
Obsługa błędów i ostrzeżeń walidacji
Błędy sprawdzania poprawności schematu XML są zgłaszane podczas sprawdzania poprawności danych XML załadowanych do modelu DOM. Otrzymasz powiadomienie o wszystkich błędach sprawdzania poprawności schematu znalezionych podczas sprawdzania poprawności danych XML podczas ich ładowania lub sprawdzania poprawności wcześniej niewaleczonego dokumentu XML.
Błędy sprawdzania poprawności są obsługiwane przez element ValidationEventHandler. ValidationEventHandler Jeśli ValidationEventHandler został przypisany do wystąpienia Validate lub przekazany do metody XmlDocument klasy ValidationEventHandler, wtedy XmlSchemaValidationException obsłuży błędy weryfikacji schematu; w przeciwnym razie zgłaszany jest .
Uwaga
Dane XML są ładowane do modelu DOM pomimo błędów weryfikacji schematu, chyba że ValidationEventHandler zgłosi wyjątek, aby zatrzymać proces.
Ostrzeżenia sprawdzania poprawności schematu nie są zgłaszane, chyba że flaga ReportValidationWarnings jest określona dla obiektu XmlReaderSettings.
Aby zapoznać się z przykładami ilustrującymi element ValidationEventHandler, zobacz "Weryfikowanie dokumentu XML jako załadowanego do modelu DOM" i "Weryfikowanie dokumentu XML w modelu DOM" powyżej.