XML Schema Unique Together on Two Attributes

2020-08-16 18:37发布

问题:

I have a simple XML structure:

<foo>
    <bar row="42" column="2"></bar>
    <bar row="42" column="3"></bar>
</foo>

I would like row and column of bar to be unique together. So the above example validates, whereas the following does not:

<foo>
    <bar row="42" column="2"></bar>
    <bar row="42" column="3"></bar>
    <bar row="42" column="3"></bar>
</foo>

I've been trying to add a key to the following schema, but I haven't found a solution yet.

<xs:element name="foo">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="bar" minOccurs="1" maxOccurs="unbounded">
                <xs:complexType>
                    <xs:simpleContent>
                        <xs:extension base="xs:string">
                            <xs:attribute name="row" type="xs:positiveInteger" use="required"/>
                            <xs:attribute name="column" type="xs:positiveInteger" use="required"/>
                        </xs:extension>
                    </xs:simpleContent>
                </xs:complexType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>
</xs:element>

回答1:

I would expect the following to do it.

<xsd:element name="foo">
  ...
  <xsd:unique name="rowcol">
    <xsd:selector xpath="bar"/>
    <xsd:field xpath="@row"/>
    <xsd:field xpath="@column"/>
  </xsd:unique>
</xsd:element>

The uniqueness contraint goes inside the element declaration for uniqueness scope, which I surmise is foo. If your structure is actually more like:

<root>
  <foo> ... </foo>
  <foo> ... </foo>
</root>

And you want the uniqueness to be global, then the constraint should go on root.



标签: xml xsd