【发布时间】:2019-11-22 16:45:45
【问题描述】:
一个简单的 XML:
<?xml version="1.0"?>
<root>
<code>
<command name="EXPORT"/>
</code>
<module name="DEMO_">
<keyword name="TEST123"/>
</module>
<!--
<code>
<command name="321TEST" foo="bar"/>
<keyword name="TEST123"/>
</code>
-->
</root>
还有一个简单的架构:
<?xml version='1.0'?>
<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:simpleType name='name'>
<xs:restriction base='xs:string'>
<xs:pattern value='[A-Z]*'/>
</xs:restriction>
</xs:simpleType>
<xs:element name='root'>
<xs:complexType>
<xs:choice minOccurs='0' maxOccurs='unbounded'>
<xs:element name='module'/>
<xs:element name='code'/>
</xs:choice>
</xs:complexType>
</xs:element>
<xs:element name='code'>
<xs:complexType>
<xs:choice minOccurs='0' maxOccurs='unbounded'>
<xs:element name='command'/>
</xs:choice>
</xs:complexType>
</xs:element>
<xs:element name='command'>
<xs:complexType>
<xs:attribute name='name' type='name' use='required'/>
</xs:complexType>
</xs:element>
<xs:element name='module'>
<xs:complexType>
<xs:attribute name='name' type='name' use='required'/>
</xs:complexType>
</xs:element>
</xs:schema>
<root> 中允许有任意数量的<code> 和<module>; <code> 可以包含任意数量的<command>; <command> 和 <module> 有一个必需的属性 name,它必须只包含大写字母。就是这样。
上面的 XML 被这个架构错误:
-
<module>元素的name包含下划线。 -
<module>元素包含一个从未定义或允许的<keyword>元素。
但是xmllint 和https://www.liquid-technologies.com/online-xsd-validator(至少)仍然说它是有效的:
$ xmllint --schema test.xsd test.xml --noout
test.xml validates
我错过了什么?
如果我取消注释最后一个元素,我会收到无效 name 和不允许的属性 foo 的错误(但仍然不是 <keyword> 元素)。这样就完成了某种验证。
【问题讨论】:
标签: xml validation xsd