Memvalidasi Dokumen XML di DOM
KelasXmlDocument tidak memvalidasi XML dalam Model Objek Dokumen (DOM) terhadap skema bahasa pemrogram definisi Skema XML (XSD) atau definisi tipe dokumen (DTD) secara default; XML hanya diverifikasi agar terbentuk dengan baik.
Untuk memvalidasi XML di DOM, Anda dapat memvalidasi XML seperti yang dimuat ke dalam DOM dengan meneruskan validasi skema XmlReader ke Load metode XmlDocument kelas, atau memvalidasi dokumen XML yang sebelumnya tidak valid di DOM menggunakan Validate metode XmlDocument kelas.
Memvalidasi Dokumen XML Saat Dimuat ke dalam DOM
Kelas XmlDocument memvalidasi data XML saat dimuat ke dalam DOM saat validasi XmlReader diteruskan ke Load metode XmlDocument kelas.
Setelah validasi berhasil, default skema diterapkan, nilai teks dikonversi ke nilai atom seperlunya, dan informasi jenis dikaitkan dengan item informasi yang divalidasi. Akibatnya, data XML yang diketik menggantikan data XML yang sebelumnya tidak diketik.
Membuat XML Validasi Skema XmlReader
Untuk membuat validasi skema XML XmlReader, ikuti langkah-langkah ini.
Buat XmlReaderSettings instans baru.
Tambahkan skema XML ke Schemas properti XmlReaderSettings instans.
Menentukan
Schema
sebagai ValidationType.Secara opsional tentukan ValidationFlags dan ValidationEventHandler untuk menangani kesalahan validasi skema dan peringatan yang ditemui selama validasi.
Terakhir, teruskan XmlReaderSettings objek ke Create metode XmlReader kelas bersama dengan dokumen XML, membuat validasi XmlReaderskema.
Contoh
Dalam contoh kode berikut, validasi XmlReader skema memvalidasi data XML yang dimuat ke dalam DOM. Modifikasi tidak valid dilakukan pada dokumen XML dan dokumen kemudian divalidasi ulang, menyebabkan kesalahan validasi skema. Akhirnya, salah satu kesalahan dikoreksi, lalu bagian dari dokumen XML divalidasi sebagian.
#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
Contoh menggunakan file contosoBooks.xml
sebagai input.
<?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>
Contoh menggunakan contosoBooks.xsd
file sebagai input.
<?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>
Mempertimbangkan hal berikut saat memvalidasi data XML saat dimuat ke dalam DOM.
Dalam contoh di atas, ValidationEventHandler dipanggil setiap kali jenis yang tidak valid ditemui. Jika ValidationEventHandler tidak diatur pada validasi XmlReader, XmlSchemaValidationException dilempar saat Load dipanggil jika ada atribut atau jenis elemen yang tidak cocok dengan jenis terkait yang ditentukan dalam skema validasi.
Saat dokumen XML dimuat ke dalam objek XmlDocument dengan skema terkait yang menentukan nilai default, objek XmlDocument memperlakukan default ini seolah-olah muncul di dokumen XML. Ini berarti bahwa IsEmptyElement properti selalu kembali
false
untuk elemen yang default dari skema. Bahkan jika dalam dokumen XML, itu ditulis sebagai elemen kosong.
Memvalidasi Dokumen XML di DOM
Metode ValidateXmlDocument kelas memvalidasi data XML yang dimuat dalam DOM terhadap skema di XmlDocument properti objek Schemas. Setelah validasi berhasil, default skema diterapkan, nilai teks dikonversi ke nilai atom seperlunya, dan informasi jenis dikaitkan dengan item informasi yang divalidasi. Akibatnya, data XML yang diketik menggantikan data XML yang sebelumnya tidak diketik.
Contoh di bawah ini mirip dengan contoh dalam "Memvalidasi Dokumen XML Saat Dimuat ke dalam DOM" di atas. Dalam contoh ini, dokumen XML tidak divalidasi karena dimuat ke dalam DOM, melainkan divalidasi setelah dimuat ke dalam DOM menggunakan Validate metode XmlDocument kelas. Metode Validate memvalidasi dokumen XML terhadap skema XML yang terkandung dalam Schemas properti dari XmlDocument. Modifikasi tidak valid dilakukan pada dokumen XML dan dokumen kemudian divalidasi ulang, menyebabkan kesalahan validasi skema. Akhirnya, salah satu kesalahan dikoreksi, lalu bagian dari dokumen XML divalidasi sebagian.
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
Contoh mengambil sebagai input file contosoBooks.xml
dan contosoBooks.xsd
yang disebutkan dalam "Memvalidasi Dokumen XML seperti yang Dimuat ke dalam DOM" di atas.
Menangani Kesalahan dan Peringatan Validasi
Kesalahan validasi skema XML dilaporkan saat memvalidasi data XML yang dimuat di DOM. Anda diberi tahu tentang semua kesalahan validasi skema yang ditemukan saat memvalidasi data XML saat sedang dimuat, atau ketika memvalidasi dokumen XML yang sebelumnya tidak valid.
Kesalahan validasi ditangani oleh ValidationEventHandler. ValidationEventHandler Jika ditetapkan ke XmlReaderSettings instans, atau diteruskan ke Validate metode XmlDocument kelas, ValidationEventHandler akan menangani kesalahan validasi skema; jika tidakXmlSchemaValidationException, akan muncul saat kesalahan validasi skema ditemui.
Catatan
Data XML dimuat ke dalam DOM meskipun ada kesalahan validasi skema kecuali Anda ValidationEventHandler menimbulkan pengecualian untuk menghentikan proses.
Peringatan validasi skema tidak dilaporkan kecuali ReportValidationWarnings bendera ditentukan ke XmlReaderSettings objek.
Untuk contoh yang mengilustrasikan ValidationEventHandler, lihat "Memvalidasi Dokumen XML Saat Dimuat ke dalam DOM" dan "Memvalidasi Dokumen XML di DOM" di atas.