[英]XML element not validated using XSD
我對通過XML驗證和XSD架構存在問題。 假設我具有以下結構:
<?xml version="1.0" encoding="utf-8"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Category1>
<Elementb>a</Elementb>
<Element2>1</Element2>
<Element3>1.0</Element3>
</Category1>
<Category2>
<Element4>b</Element4>
<Element5>c</Element5>
</Category2>
</Root>
還有以下模式:
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="unqualified">
<xs:element name="Root">
<xs:complexType>
<xs:all>
<xs:element name="Category1" type="category1Type" minOccurs="0"/>
<xs:element name="Category2" type="category2Type" minOccurs="0"/>
</xs:all>
</xs:complexType>
</xs:element>
<xs:complexType name="category1Type">
<xs:all>
<xs:element name="Element1" type="xs:token" minOccurs="0"/>
<xs:element name="Element2" type="xs:integer" minOccurs="0"/>
<xs:element name="Element3" type="xs:decimal" minOccurs="0"/>
</xs:all>
</xs:complexType>
<xs:complexType name="category2Type">
<xs:all>
<xs:element name="Element4" type="xs:token" minOccurs="0"/>
<xs:element name="Element5" type="xs:token" minOccurs="0"/>
</xs:all>
</xs:complexType>
</xs:schema>
好的,“ Elementb”不會驗證,因為它未在模式中定義。 這是故意的。 假設我們使用以下代碼進行驗證:
foreach (XmlNode rootNode in document)
{
foreach (XmlNode category in rootNode)
{
foreach (XmlElement element in category)
{
document.Validate(ValidationCallBack, element);
}
}
}
意思是我要逐個進行驗證。 問題在於,在這種情況下,不僅<Elementb>
會在調用Validate時引發異常,而且還會在該類別中引發以下元素。 這是為什么? 我想念什么? 我認為通過使用xs:all
和minOccurs="0"
,順序無關緊要,並且由於缺少<Element1>
,因此<Element2>
應進行驗證。 有任何想法嗎? 謝謝。
我認為是因為您只是要求它進行驗證
<Element2>1</Element2>
它沒有元素2在文檔中的位置的上下文,因此將其視為根元素。 這對於XML模式無效,因為定義的唯一根元素是“ Root”。
您也許可以將模式更改為如下所示,但是從根目錄驗證文檔並在驗證處理程序中處理結果更為正常
<?xml version="1.0" encoding="utf-8" ?>
<!--Created with Liquid Studio 2018 (https://www.liquid-technologies.com)-->
<xs:schema elementFormDefault="unqualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Root">
<xs:complexType>
<xs:all>
<xs:element name="Category1"
type="category1Type"
minOccurs="0" />
<xs:element name="Category2"
type="category2Type"
minOccurs="0" />
</xs:all>
</xs:complexType>
</xs:element>
<xs:complexType name="category1Type">
<xs:all>
<xs:element ref="Element1"
minOccurs="0" />
<xs:element ref="Element2"
minOccurs="0" />
<xs:element ref="Element3"
minOccurs="0" />
</xs:all>
</xs:complexType>
<xs:complexType name="category2Type">
<xs:all>
<xs:element ref="Element4"
minOccurs="0" />
<xs:element ref="Element5"
minOccurs="0" />
</xs:all>
</xs:complexType>
<xs:element name="Element1"
type="xs:token" />
<xs:element name="Element2"
type="xs:integer" />
<xs:element name="Element3"
type="xs:decimal" />
<xs:element name="Element4"
type="xs:token" />
<xs:element name="Element5"
type="xs:token" />
</xs:schema>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.