我目前正在努力处理 XML Schema 1.1 中的断言。XML Schema 1.1 建议指出,如果在执行期间发生错误,则违反了断言。这种行为似乎是合理的,但在尝试理解评估结果时可能会引起一些混乱。让我解释:
以下示例 XSD 解释定义了两个元素:str 和 dec。元素 str 必须具有值“A”或“B”。元素 dec 必须是数字。此外,如果 str 的值为“A”,则 dec 必须为正数。我试图通过使用断言来定义最后一个属性:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="data">
<xs:complexType>
<xs:sequence>
<xs:element name="str">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="A"/>
<xs:enumeration value="B"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="dec" type="xs:decimal"/>
</xs:sequence>
<xs:assert test="str != 'A' or dec gt 0"/>
</xs:complexType>
</xs:element>
</xs:schema>
以下 XML 文件无效,因为元素 str 具有值“X”,这是不允许的。
<?xml version="1.0" encoding="utf-8" ?>
<data>
<str>X</str>
<dec>5</dec>
</data>
当我现在使用 Saxon 9.6.0.6 验证 XML 文件时,我得到以下输出:
Validation error on line 3 column 16 of test.xml:
XSD: The content "X" of element <str> does not match the required simple type. Value "X"
contravenes the enumeration facet "A, B" of the type of element str
Validating /data[1]/str[1]
See http://www.w3.org/TR/xmlschema11-2/#cvc-datatype-valid clause 1
Warning: on line 1
Internal error: value doesn't match its type annotation. Value "X" contravenes the
enumeration facet "A, B" of the type of element str
Validation error at data on line 5 column 8 of test.xml:
XSD: Element data does not satisfy assertion str != 'A' or dec gt 0
Validating /data[1]
如您所见,仅针对一个问题(元素 str 的值非法)报告了两个错误。我发现这种行为非常令人困惑,因为它使我们更难看到真正的问题(错误的值,而不是失败的断言)。
有什么方法可以“捕获”断言中的类型错误,以便在此示例中断言不会失败?