Ran*_*yaa 2 xml validation schema xsd
我试图验证的XML如下:
<root>
<element attribute="foo">
<bar/>
</element>
<element attribute="hello">
<world/>
</element>
</root>
Run Code Online (Sandbox Code Playgroud)
如何使用Schema验证?
注意:
当attribute ="foo"时,element只能包含bar.
attribute ="hello"时,element只能包含world
您无法在XML Schema 1.0中执行此操作.在XML Schema 1.1中,你将能够使用该<xs:assert>元素来完成它,但我猜你想要一些你现在可以使用的东西.
您可以使用Schematron作为第二层验证,它允许您测试有关XML文档的任意XPath断言.有一篇关于在XSD中嵌入Schematron的相当古老的文章,你可能会发现它很有帮助.
你会做类似的事情:
<rule context="element">
<report test="@attribute = 'foo' and *[not(self::bar)]">
This element's attribute is 'foo' but it holds an element that isn't a bar.
</report>
<report test="@attribute = 'hello' and *[not(self::world)]">
This element's attribute is 'hello' but it holds an element that isn't a world.
</report>
</rule>
Run Code Online (Sandbox Code Playgroud)
或者当然你可以切换到RELAX NG,它在睡眠中这样做:
<element name="element">
<choice>
<group>
<attribute name="attribute"><value>foo</value></attribute>
<element name="bar"><empty /></element>
</group>
<group>
<attribute name="attribute"><value>hello</value></attribute>
<element name="world"><empty /></element>
</group>
</choice>
</element>
Run Code Online (Sandbox Code Playgroud)