基于属性限制元素值 [英] Restrict Element Values Based on Attribute
问题描述
我想根据属性的值来限制元素的类型,如下所示:
I want to restrict the type of an Element based on the value of an Attribute, like this:
<数据类型="十进制">44.00</数据>
<Data type="decimal"> 44.00 </Data>
<数据类型="日期">2008-02-01</数据>
<Data type="date"> 2008-02-01 </Data>
可以定义一个 Schema 来做到这一点吗?
Can a Schema be defined that does this?
推荐答案
众所周知,XML-Schema 无法做到这一点,
It's a well known fact that, XML-Schema can't do this,
基于另一个元素的元素验证被视为不明确的,因此不可能.但是如果你愿意,你可以验证两种类型的数据类型而忽略条件验证,就像这样:
validation of an element based on the other element is treated as ambiguous, so not possible. But if you want, you can validate both type of data-types ignoring the conditional validation, something like this:
用自定义名称定义一个新的数据类型,然后复制粘贴下面写的模式.
Define a new data type with custom name, and copy paste the pattern written below.
<xs:simpleType name="new_type">
<xs:restriction base="xs:string">
<xs:pattern value="(([0-9]+)[.]([0-9]+))|(([0][1-9]|[1][0-2])/([0][1-9]|[1-2][0-9]|[3][0-1])/[1-2][0-9][0-9][0-9])"/>
</xs:restriction>
</xs:simpleType>
这将接受类型为小数或日期的数据,但您无法使用属性值对其进行验证,
This will accept the Data of type decimal or date, but you cannot validate it with the attribute values,
另一种解决方案是使用 Schematron,但您不会像 XSD 和 XSLT 那样获得如此方便和用户友好的工具.
The alternative solution is to use Schematron, but you won't get so handy and user-friendly tool for that as you get in-case of XSD and XSLT.
这篇关于基于属性限制元素值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!