簡體   English   中英

使元素內容在 xsd 中唯一

[英]Make content of element unique in xsd

我有一個元素:

<xsd:element name="tags" type="tagsType"></xsd:element>

這是tagsType

<xsd:complexType name="tagsType">
        <xsd:sequence>
            <xsd:element name="t" minOccurs="0" maxOccurs="unbounded">
                <xsd:complexType>
                    <xsd:simpleContent>
                        <xsd:extension base="xsd:string">
                            <xsd:attribute name="tagname" type="xsd:string"></xsd:attribute>
                        </xsd:extension>
                    </xsd:simpleContent>
                </xsd:complexType>
                <xsd:key name="tagKey">
                    <xsd:selector xpath="tags/tag"/>
                    <xsd:field xpath="@tagname"/>
                </xsd:key>
            </xsd:element>
        </xsd:sequence>
</xsd:complexType>

我如何將tagname名屬性限制為唯一,但我想讓該標記的內容也唯一。 例子:

<tags>
    <t>tag1</t>
    <t>tag1</t>
    <t>tag2</t>
</tags>

這不應該驗證,因為重復的tag1 這應該驗證:

<tags>
    <t>tag1</t>
    <t>tag2</t>
    <t>tag3</t>
</tags>

我如何實現這一目標?

您可以使用以下 XSD 獲得所需的結果。
它使用xsd:unique元素來確保值是唯一的。

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">

    <xsd:complexType name="tagsType">
        <xsd:sequence>
            <xsd:element name="t" type="xsd:string"  minOccurs="0" maxOccurs="unbounded" />
        </xsd:sequence>
    </xsd:complexType>
    
    <xsd:element name="tags" type="tagsType">
        <xsd:unique name="t_unique" >
            <xsd:selector xpath="t"/>
            <xsd:field xpath="."/>
        </xsd:unique>
    </xsd:element>
    
</xsd:schema>

此 XSD 驗證第二個 XML 並在第一個上失敗。


xsd:unique元素有兩個子元素:

xsd:unique 元素必須包含以下內容(按順序):

  • 一個也是唯一一個 xsd:selector 元素(包含一個 XPath 表達式,該表達式指定一組元素,字段指定的值必須在其中唯一)
  • 一個或多個 xsd:field 元素(包含一個 XPath 表達式,該表達式指定對於選擇器元素指定的元素集必須唯一的值)

如果您希望 Y 中的每個 X 對 Z 具有唯一值,則:

(a) Y 的聲明應該持有xs:unique約束

(b) 選擇器應該是從 Y 開始選擇 X 的路徑表達式

(c) 該字段應該是從 X 開始選擇 Z 的路徑表達式。

因此,您所犯的根本錯誤是將約束定義在錯誤的級別。 xs:unique不屬於你想要唯一的東西,它屬於它需要唯一的包含元素。

這是因為元素的有效性僅取決於其內容,而不取決於其上下文。 如果兩個 X 的 Z 值相同,則包含的 Y 無效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM