元素的类型可以有唯一的约束吗?
假设我有一艘诺亚方舟,其中 Animal/@name 必须是唯一的。
下面是一个未根据架构进行验证的 XML:
<ns:NoahsArk xmlns:ns="http://www.xxx.com" xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" xs:schemaLocation="http://www.xxx.com Persons.xsd">
<Animal xs:type="ns:Dog" ns:name="Gipsy" ns:pedigree="caniche"/>
<Animal xs:type="ns:Spider" ns:name="Gipsy" ns:legNumber="5"/>
</ns:NoahsArk>
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:ns="http://www.xxx.com"
targetNamespace="http://www.xxx.com" elementFormDefault="unqualified" attributeFormDefault="qualified">
<xs:element name="NoahsArk">
<xs:complexType>
<xs:sequence>
<xs:element name="Animal" maxOccurs="unbounded" type="ns:Animal"/>
</xs:sequence>
</xs:complexType>
<xs:unique name="NameUnicity">
<xs:selector xpath="Animal"/>
<xs:field xpath="@ns:name"/>
</xs:unique>
</xs:element>
<xs:complexType name="Animal" abstract="true">
<xs:attribute name="name" type="xs:string" use="required"/>
</xs:complexType>
<xs:complexType name="Dog">
<xs:complexContent>
<xs:extension base="ns:Animal">
<xs:attribute name="pedigree" type="xs:string" use="required"/>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="Spider">
<xs:complexContent>
<xs:extension base="ns:Animal">
<xs:attribute name="legNumber" type="xs:integer" use="required"/>
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:schema>
这很好,但现在假设我想要一艘诺亚方舟,其中 Animal/@xsi:type 是独一无二的。
我尝试了这个约束:
<xs:unique name="AnimalUnicity">
<xs:selector xpath="Animal"/>
<xs:field xpath="@xs:type"/>
</xs:unique>
但这个 XML 仍然有效:(
<?xml version="1.0" encoding="UTF-8"?>
<ns:NoahsArk xmlns:ns="http://www.xxx.com" xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" xs:schemaLocation="http://www.xxx.com Persons.xsd">
<Animal xs:type="ns:Dog" ns:name="Pierre-Louis" ns:pedigree="doberman"/>
<Animal xs:type="ns:Spider" ns:name="Gipsy" ns:legNumber="5"/>
</ns:NoahsArk>
有任何想法吗 ?
谢谢,
-E
感谢您的答复。
只是为了好玩,我尝试了 Schematron;但是我无法让它工作,因为我发现的 XPath 表达式使用“current()”,而它在氧气或 XMLSpy 中不可用,所以我无法测试它:(
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.ascc.net/xml/schematron" xmlns:ns="http://www.xxx.com" >
<ns prefix="ns" uri="http://www.xxx.com"/>
<ns prefix="xs" uri="http://www.w3.org/2001/XMLSchema-instance"/>
<pattern name="AnimalNameUnicity">
<rule context="Animals/Animal">
<assert test="count(//@ns:name[ . = current()]) > 1">name not unique !</assert>
</rule>
</pattern>
</schema>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)