好的,基本上我目前拥有的是:
XSD:
<?xml version="1.0"?>
<xsd:schema xmlns="test"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="test"
elementFormDefault="qualified">
<xsd:complexType name="fields">
<xsd:choice minOccurs="1" maxOccurs="unbounded">
<xsd:element name="text">
<xsd:complexType>
<xsd:attribute name="id" type="xsd:string" use="required"/>
</xsd:complexType>
</xsd:element>
<xsd:element name="group">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="fields" type="fields"/>
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string" use="required"/>
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
<xsd:element name="root">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="fields" type="fields" minOccurs="0" maxOccurs="unbounded">
<xsd:key name="fieldId">
<xsd:selector xpath=".//*"/>
<xsd:field xpath="@id"/>
</xsd:key>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
XML:
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns="test">
<fields>
<text id="asd"/>
<text id="sdf"/>
<group id="dfg">
<fields>
<text id="asd"/>
<text id="sdf"/>
</fields>
</group>
</fields>
</root>
显然,根据 XSD,XML 无效,因为存在重复的 ID,但问题是,我希望仅在其自己的范围内验证 id,换句话说,这应该失败:
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns="test">
<fields>
<text id="asd"/>
<text id="asd"/>
</fields>
</root>
虽然这应该通过:
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns="test">
<fields>
<text id="asd"/>
<group id="sdf">
<fields>
<text id="asd"/>
</fields>
</group>
</fields>
</root>
为了清楚起见,我计划在解析 XML 时将父 ID 添加到子 ID,因此我不关心嵌套 ID 是否重复,而它们不在同一范围内,因为我希望能够实现类似的结果:
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns="test">
<fields>
<group id="eventA_time">
<fields>
<text id="hour"/>
<text id="minute"/>
<text id="second"/>
</fields>
</group>
<group id="eventB_time">
<fields>
<text id="hour"/>
<text id="minute"/>
<text id="second"/>
</fields>
</group>
</fields>
</root>