如何使用架构基于属性值验证元素? [英] How can you validate Elements based on an attribute Value using a Schema?
问题描述
我要验证的 XML 如下:
<元素属性="foo"><酒吧/></元素><元素属性=你好"><世界/></元素></root>
如何使用架构进行验证?
注意:
元素只能在attribute="foo"时包含bar.
element 只能包含 world 当 attribute="hello"
您不能在 XML Schema 1.0 中执行此操作.在 XML Schema 1.1 中,您将能够使用 <xs:assert>
元素来做这件事,但我猜你想要一些你现在可以使用的东西.
您可以使用 Schematron 作为第二层验证,允许您测试关于您的 XML 文档.有一篇关于在 XSD 中嵌入 Schematron 的相当老的文章,您可能会觉得有帮助.>
你会做这样的事情:
<report test="@attribute = 'foo' and *[not(self::bar)]">这个元素的属性是 'foo' 但它包含一个不是 bar 的元素.</报告><report test="@attribute = 'hello' and *[not(self::world)]">这个元素的属性是 'hello' 但它包含一个不是世界的元素.</报告></规则>
当然,您也可以切换到 RELAX NG,它会在睡眠中执行此操作:
<元素名称="元素"><选择><组><attribute name="attribute"><value>foo</value></attribute><element name="bar"><empty/></element></组><组><attribute name="attribute"><value>hello</value></attribute><element name="world"><empty/></element></组>选择></元素>
The XML I'm trying to validate is as follows:
<root>
<element attribute="foo">
<bar/>
</element>
<element attribute="hello">
<world/>
</element>
</root>
How can this be validated using a Schema?
Note:
element can only contain bar when attribute="foo".
element can only contain world when attribute="hello"
You can't do this in XML Schema 1.0. In XML Schema 1.1 you will be able to use the <xs:assert>
element to do it, but I'm guessing you want something that you can use now.
You can use Schematron as a second layer of validation that will allow you to test arbitrary XPath assertions about your XML document. There's a fairly old article about embedding Schematron in XSD that you might find helpful.
You'd do something like:
<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>
Or of course you can switch to RELAX NG, which does this in its sleep:
<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>
这篇关于如何使用架构基于属性值验证元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!