[英]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.