您可以使用 類別 XmlDocument ,以兩種方式驗證 物件中包含的 XmlDocument XML 內容。 第一種方式是使用驗證對象來驗證 XmlReader XML 內容,第二種方式是使用 Validate 類別的 XmlDocument 方法。 您也可以使用 XPathDocument 類別執行 XML 內容的唯讀驗證。
驗證 XML 數據
類別 XmlDocument 預設不會使用 DTD 或 XML 架構定義語言 (XSD) 架構驗證來驗證 XML 檔。 它只會驗證 XML 檔的格式是否正確。
驗證 XML 文件的第一種方法是,在將文件載入 `XmlDocument` 物件時,使用 `XmlReader` 驗證物件進行驗證。 第二種方式是使用 Validate 類別的 XmlDocument 方法驗證先前不具類型的 XML 檔。 在這兩種情況下,可以使用Validate類別的XmlDocument方法來重新驗證對已驗證的 XML 文件所做的更改。
當文件載入時進行檢驗
驗證XmlReader對象是藉由將XmlReaderSettings對象傳遞至Create類別的XmlReader方法,此方法接受XmlReaderSettings物件作為參數來建立。
XmlReaderSettings 當作參數傳遞的物件,其 ValidationType 屬性被設定為 Schema
,而 XmlDocument 物件中的 XML 文件包含這個 XML 架構,並已加入到其 Schemas 屬性。 然後,驗證 XmlReader 物件會用來建立 XmlDocument 物件。
以下範例在將contosoBooks.xml
檔案載入XmlDocument物件時,透過使用帶有驗證功能的XmlDocument物件來建立XmlReader物件,從而驗證contosoBooks.xml
檔案。 由於 XML 檔根據其架構有效,因此不會產生任何架構驗證錯誤或警告。
Imports System
Imports System.Xml
Imports System.Xml.Schema
Imports System.Xml.XPath
Class ValidatingReaderExample
Shared Sub Main(ByVal args() As String)
Try
Dim settings As XmlReaderSettings = New XmlReaderSettings()
settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd")
settings.ValidationType = ValidationType.Schema
Dim reader As XmlReader = XmlReader.Create("contosoBooks.xml", settings)
Dim document As XmlDocument = New XmlDocument()
document.Load(reader)
Dim navigator As XPathNavigator = document.CreateNavigator()
Catch e As Exception
Console.WriteLine("ValidatingReaderExample.Exception: {0}", e.Message)
End Try
End Sub
Shared Sub SchemaValidationHandler(ByVal sender As Object, ByVal e As ValidationEventArgs)
Select Case e.Severity
Case XmlSeverityType.Error
Console.WriteLine("Schema Validation Error: {0}", e.Message)
Exit Sub
Case XmlSeverityType.Warning
Console.WriteLine("Schema Validation Warning: {0}", e.Message)
Exit Sub
End Select
End Sub
End Class
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
class ValidatingReaderExample
{
static void Main(string[] args)
{
try
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd");
settings.ValidationType = ValidationType.Schema;
XmlReader reader = XmlReader.Create("contosoBooks.xml", settings);
XmlDocument document = new XmlDocument();
document.Load(reader);
XPathNavigator navigator = document.CreateNavigator();
}
catch (Exception e)
{
Console.WriteLine("ValidatingReaderExample.Exception: {0}", e.Message);
}
}
static void SchemaValidationHandler(object sender, ValidationEventArgs e)
{
switch (e.Severity)
{
case XmlSeverityType.Error:
Console.WriteLine("Schema Validation Error: {0}", e.Message);
break;
case XmlSeverityType.Warning:
Console.WriteLine("Schema Validation Warning: {0}", e.Message);
break;
}
}
}
此範例會將 contosoBooks.xml
檔案當作輸入。
<?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>
此範例也會採用 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>
在上述範例中,當呼叫 XmlSchemaValidationException 時,如果任何屬性或元素類型不符合驗證架構中指定的對應類型,則會擲回 Load。 如果在驗證ValidationEventHandler時設置XmlReader,那麼每當遇到無效的類型時,就會呼叫ValidationEventHandler。
當設定為 XmlSchemaException 的屬性或元素 TypedValue 被 invalid
存取時,將會擲回 XPathNavigator。
可以使用Validity屬性來判斷當使用XPathNavigator存取屬性或元素時,個別屬性或元素是否有效。
備註
當 XML 檔載入 XmlDocument 具有定義預設值之相關聯架構的物件時, XmlDocument 物件會將這些預設值視為出現在 XML 檔中。 這表示,對於從架構預設的元素,屬性 IsEmptyElement 一律會傳回 false
,即使在 XML 文件中它是作為空元素寫入的也是如此。
使用驗證方法驗證文件
類別Validate的 XmlDocument 方法會根據物件 XmlDocument 屬性中指定的XmlDocument架構,驗證 物件中包含的 Schemas XML 檔,並執行資訊集增強。 結果是在 XmlDocument 物件中,先前不具類型的 XML 檔被替換為具有類型的檔案。
物件會藉由將委派作為參數傳遞給 XmlDocument 方法來報告架構驗證錯誤和警告,使用 ValidationEventHandler 和 Validate。
下列範例會驗證contosoBooks.xml
物件中包含的XmlDocument檔案是否符合contosoBooks.xsd
物件的XmlDocument屬性中所包含的Schemas架構。
Imports System
Imports System.Xml
Imports System.Xml.Schema
Imports System.Xml.XPath
Class ValidateExample
Shared Sub Main(ByVal args() As String)
Dim document As XmlDocument = New XmlDocument()
document.Load("contosoBooks.xml")
Dim navigator As XPathNavigator = document.CreateNavigator()
document.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd")
Dim validation As ValidationEventHandler = New ValidationEventHandler(AddressOf SchemaValidationHandler)
document.Validate(validation)
End Sub
Shared Sub SchemaValidationHandler(ByVal sender As Object, ByVal e As ValidationEventArgs)
Select Case e.Severity
Case XmlSeverityType.Error
Console.WriteLine("Schema Validation Error: {0}", e.Message)
Exit Sub
Case XmlSeverityType.Warning
Console.WriteLine("Schema Validation Warning: {0}", e.Message)
Exit Sub
End Select
End Sub
End Class
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
class ValidateExample
{
static void Main(string[] args)
{
XmlDocument document = new XmlDocument();
document.Load("contosoBooks.xml");
XPathNavigator navigator = document.CreateNavigator();
document.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd");
ValidationEventHandler validation = new ValidationEventHandler(SchemaValidationHandler);
document.Validate(validation);
}
static void SchemaValidationHandler(object sender, ValidationEventArgs e)
{
switch (e.Severity)
{
case XmlSeverityType.Error:
Console.WriteLine("Schema Validation Error: {0}", e.Message);
break;
case XmlSeverityType.Warning:
Console.WriteLine("Schema Validation Warning: {0}", e.Message);
break;
}
}
}
此範例會將 contosoBooks.xml
檔案當作輸入。
<?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>
此範例也會採用 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>
验证修改
對 XML 檔案進行了修改後,可以使用 Validate 類別的 XmlDocument 方法,依綱要驗證 XML 文件的修改。
以下範例在將contosoBooks.xml
檔案載入XmlDocument物件時,透過使用帶有驗證功能的XmlDocument物件來建立XmlReader物件,從而驗證contosoBooks.xml
檔案。 XML 檔會在載入時成功驗證,而不會產生任何架構驗證錯誤或警告。 然後,此範例會根據架構對無效的 contosoBooks.xsd
XML 檔進行兩項修改。 第一次修改會插入無效的子元素,導致結構驗證錯誤,而第二次修改會將具類型節點的值設為該類型無效的值,從而導致例外狀況。
Imports System
Imports System.Xml
Imports System.Xml.Schema
Imports System.Xml.XPath
Class ValidatingReaderExample
Shared Sub Main(ByVal args() As String)
Try
Dim settings As XmlReaderSettings = New XmlReaderSettings()
settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd")
settings.ValidationType = ValidationType.Schema
Dim reader As XmlReader = XmlReader.Create("contosoBooks.xml", settings)
Dim document As XmlDocument = New XmlDocument()
document.Load(reader)
Dim navigator As XPathNavigator = document.CreateNavigator()
Dim validation As ValidationEventHandler = New ValidationEventHandler(AddressOf SchemaValidationHandler)
navigator.MoveToChild("bookstore", "http://www.contoso.com/books")
navigator.MoveToChild("book", "http://www.contoso.com/books")
navigator.MoveToChild("author", "http://www.contoso.com/books")
navigator.AppendChild("<title>Book Title</title>")
document.Validate(validation)
navigator.MoveToParent()
navigator.MoveToChild("price", "http://www.contoso.com/books")
navigator.SetTypedValue(DateTime.Now)
Catch e As Exception
Console.WriteLine("ValidatingReaderExample.Exception: {0}", e.Message)
End Try
End Sub
Shared Sub SchemaValidationHandler(ByVal sender As Object, ByVal e As ValidationEventArgs)
Select Case e.Severity
Case XmlSeverityType.Error
Console.WriteLine("Schema Validation Error: {0}", e.Message)
Exit Sub
Case XmlSeverityType.Warning
Console.WriteLine("Schema Validation Warning: {0}", e.Message)
Exit Sub
End Select
End Sub
End Class
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
class ValidatingReaderExample
{
static void Main(string[] args)
{
try
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd");
settings.ValidationType = ValidationType.Schema;
XmlReader reader = XmlReader.Create("contosoBooks.xml", settings);
XmlDocument document = new XmlDocument();
document.Load(reader);
XPathNavigator navigator = document.CreateNavigator();
ValidationEventHandler validation = new ValidationEventHandler(SchemaValidationHandler);
navigator.MoveToChild("bookstore", "http://www.contoso.com/books");
navigator.MoveToChild("book", "http://www.contoso.com/books");
navigator.MoveToChild("author", "http://www.contoso.com/books");
navigator.AppendChild("<title>Book Title</title>");
document.Validate(validation);
navigator.MoveToParent();
navigator.MoveToChild("price", "http://www.contoso.com/books");
navigator.SetTypedValue(DateTime.Now);
}
catch (Exception e)
{
Console.WriteLine("ValidatingReaderExample.Exception: {0}", e.Message);
}
}
static void SchemaValidationHandler(object sender, ValidationEventArgs e)
{
switch (e.Severity)
{
case XmlSeverityType.Error:
Console.WriteLine("Schema Validation Error: {0}", e.Message);
break;
case XmlSeverityType.Warning:
Console.WriteLine("Schema Validation Warning: {0}", e.Message);
break;
}
}
}
此範例會將 contosoBooks.xml
檔案當作輸入。
<?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>
此範例也會採用 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>
在上述範例中,對物件中包含的 XmlDocument XML 檔進行了兩項修改。 載入 XML 檔時,任何遇到的架構驗證錯誤都會由驗證事件處理程式方法處理,並寫入主控台。
在此範例中,驗證錯誤是在載入 XML 檔之後引入的,並使用 Validate 類別的 XmlDocument 方法找到。
使用 SetTypedValue 類別的 XPathNavigator 方法所做的修改會導致 InvalidCastException ,因為根據節點的架構類型,新值無效。
如需使用 SetTypedValue 方法修改值的詳細資訊,請參閱 使用 XPathNavigator 修改 XML 數據 主題。
Read-Only 驗證
XPathDocument 類別是 XML 文件的唯讀記憶體表示形式。 類別 XPathDocument 和 XmlDocument 類別都會建立 XPathNavigator 物件,以巡覽和編輯 XML 檔。 因為類別 XPathDocument 是只讀類別,因此從 XPathNavigator 物件傳回的 XPathDocument 物件無法編輯 XPathDocument 物件中包含的 XML 檔。
在驗證的情況下,您可以建立XPathDocument物件,就像使用驗證XmlDocument物件建立XmlReader物件一樣,如本主題稍早所述。 物件 XPathDocument 會在載入 XML 檔案時驗證 XML 檔,但因為您無法編輯物件中的 XPathDocument XML 資料,所以無法重新驗證 XML 檔。
如需只讀和可 XPathNavigator 編輯對象的詳細資訊,請參閱 使用 XPathDocument 和 XmlDocument 讀取 XML 資料 主題。