我想根据属性值验证元素的文本值。例如
<Device xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Parameter xsi:type="xsd:unsignedInt">-100</Parameter>
<Parameter xsi:type="xsd:boolean"></Parameter>
<Parameter>hello</Parameter>
</Device>
以上都应该失败。对于 bool 值,除了“true”或“false”(甚至是空字符串)外,不应接受任何内容
我的 xml 复杂得多,有很多 Object
和 Parameter
节点,这是我的 xsd,它递归地验证所有这些节点
<xs:complexType name="deviceType">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element ref="Object"/>
<xs:element ref="Parameter"/>
</xs:choice>
</xs:complexType>
<xs:complexType name="objType">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element ref="Object"/>
<xs:element ref="Parameter"/>
</xs:choice>
<!-- Add all valid attributes for 'Object' type here -->
<xs:attribute name="Id" use="required"/>
<xs:attribute name="Flag" use="required"/>
<xs:anyAttribute processContents="lax"/>
</xs:complexType>
<xs:complexType name="paramType" mixed="true">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element ref="Object"/>
<xs:element ref="Parameter"/>
</xs:choice>
<xs:attribute name="Id" use="required"/>
<xs:attribute name="Flag" use="required"/>
<xs:anyAttribute processContents="lax"/>
</xs:complexType>
但是我遇到了这个错误。
Type 'xsd:unsignedInt' is not validly derived from the type definition, 'paramType', of element 'Parameter'.
Type 'xsd:unsignedInt' is not validly derived from the type definition, 'paramType', of element 'Parameter'.
我该如何解决这个问题?
最佳答案
在您的 XML 文档中使用 xsi:type
:
声明
xsi
命名空间前缀,通常在根元素上:xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
声明
xs
(或xsd
)命名空间前缀,通常在根元素上:xmlns:xs="http://www.w3.org/2001/XMLSchema"
将任何 XSD 类型添加到您希望约束的元素:
xsi:type="xs:boolean"
这些更改直接在您的 XML 文档中进行。您不必对 XSD 进行任何更改。但是,所选类型必须有效地派生自 XSD 为给定元素提供的类型。
相关 W3C 引用资料
来自 XML Schema Part 1: Structures Second Edition ...
The Simple Type Definition (§2.2.1.2) or Complex Type Definition (§2.2.1.3) used in ·validation· of an element is usually determined by reference to the appropriate schema components. An element information item in an instance may, however, explicitly assert its type using the attribute
xsi:type
. The value of this attribute is a ·QName·; see QName Interpretation (§3.15.3) for the means by which the ·QName· is associated with a type definition.
[...]
Validation Rule: Element Locally Valid (Element)
4.3 The ·local type definition· must be validly derived from the {type definition} given the union of the {disallowed substitutions} and the {type definition}'s {prohibited substitutions}, as defined in Type Derivation OK (Complex) (§3.4.6) (if it is a complex type definition), or given {disallowed substitutions} as defined in Type Derivation OK (Simple) (§3.14.6) (if it is a simple type definition).
关于xml - 如何使用 xsi :type in XSD? 限制 XML 元素的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33808790/