2011-10-10 185 views
10

比方說,我有以下XML文件:唯一約束

<authors> 
    <author>a1</author> 
    <author>a2</author> 
    <lastmodified>2010</lastmodified> 
</authors> 

和XML schema片斷:

<xs:element name="authors" maxOccurs="1"> 
    <xs:complexType> 
    <xs:sequence> 
     <xs:element name="author" maxOccurs="unbounded" type="xs:string"> </xs:element> 
     <xs:element name="lastmodified" type="xs:date" minOccurs="0"/> 
    </xs:sequence> 
    </xs:complexType> 
    <xs:unique name="uniqueAuthor"> 
    <xs:selector xpath="."/> 
    <xs:field xpath="author"/> 
    </xs:unique> 
</xs:element> 

我要的是做一個約束,將不會允許兩個相同作者的價值觀,但上面的那個不行。我究竟做錯了什麼?

回答

16

0123rthXPath選擇必須是唯一的節點(在這種情況下,它應該選擇作者節點)。

field XPath選擇「使它們唯一」(在這種情況下,使用.將導致它們的類型值,在這種情況下,將使用標記之間的文本,將其視爲字符串)。

文件

<?xml version="1.0" encoding="UTF-8"?> 
<authors> 
    <author>a1</author> 
    <author>a2</author> 
    <lastmodified>2010-01-01</lastmodified> 
</authors> 

應該是針對以下模式是有效的:

<?xml version="1.0" encoding="UTF-8"?> 
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
    <xs:element name="authors"> 
    <xs:complexType> 
     <xs:sequence> 
     <xs:element name="author" maxOccurs="unbounded" type="xs:string"/> 
     <xs:element name="lastmodified" type="xs:date" minOccurs="0"/> 
     </xs:sequence> 
    </xs:complexType> 
    <xs:unique name="uniqueAuthor"> 
     <xs:selector xpath="author"/> 
     <xs:field xpath="."/> 
    </xs:unique> 
    </xs:element> 
</xs:schema> 

,而這其中不應該:

<?xml version="1.0" encoding="UTF-8"?> 
<authors> 
    <author>a1</author> 
    <author>a1</author> 
    <lastmodified>2010-01-01</lastmodified> 
</authors> 
1

您可以在author元素上使用type =「xs:ID」。還有類型IDREF用於引用一個ID。

+0

唯一性約束有一定的優勢超過'XS:ID ',請參閱http://www.xml.com/pub/a/2002/11/20/schemas.html#identity_constraints – DaveFar