好了,所以,基本上我目前擁有的是:如何使<xsd:key>僅適用於當前範圍?
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>
顯然XML根據XSD是無效的,因爲有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>
只是要清楚,我打算在前面加上父ID的子ID解析XML的時候,所以我不關心嵌套的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>
它確實使外部範圍工作,但它似乎像子元素都沒有驗證,所以當我在第一個字段範圍(http://pastebin.com/tvgKL2w0)中重複它處理的相同ID作爲無效(這很好),但是當我在子組(http://pastebin.com/xEbn7mFe)重複相同的ID時,它被視爲有效,這不正是我想要的。 – 2013-03-27 14:00:16