2011-10-10 186 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