Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I ensure unique element values in an XML schema?

I want to ensure that there are no duplicate book titles in the following xml:

<?xml version="1.0" encoding="UTF-8"?>
<books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="books3.xsd">
    <book>
        <title>Book1</title>
    </book>
    <book>
        <title>Book2</title>
    </book>
    <book>
        <title>Book1</title>  <!-- duplicate should not be allowed -->
    </book> 
</books>

I am using the following schema:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
  <xs:element name="books">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" ref="book"/>
      </xs:sequence>
    </xs:complexType>
    <xs:unique name="testUnique">
      <xs:selector xpath="book"/>
      <xs:field xpath="title"/>
    </xs:unique>
  </xs:element>
  <xs:element name="book">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="title"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="title" type="xs:NCName"/>
</xs:schema>

oXygen XML editor tells me this is valid when I validate.

Can anybody see what I am doing wrong?

like image 659
Nick Miller Avatar asked Mar 05 '10 12:03

Nick Miller


People also ask

What is unique attribute in XML?

<xsd:unique> ElementSpecifies that an attribute or element value (or a combination of attribute or element values) must be unique within the specified scope.

How do you make an attribute unique in XSD?

You can create a Unique constraint within an XSD using the <xs:unique> element. The selector and field pair specify the data that must be unique, the XPath expressions are relative to the parent element (Directory).

How do I restrict attribute values in XML schema?

Restrictions on a Set of Values To limit the content of an XML element to a set of acceptable values, we would use the enumeration constraint. Note: In this case the type "carType" can be used by other elements because it is not a part of the "car" element.

Do XML tags have to be unique?

A name must not appear more than once in an XML document as a value of this type; i.e., ID values must uniquely identify the elements which bear them.


1 Answers

the schema seems ok and should detect the duplicate. may be a bug in Oxygen?

you can try this site to validate your xml : http://www.xmlvalidation.com

and you'll see it finds errors in your xmldocument:

Duplicate unique value [Book1] declared for identity constraint of element "books"

like image 85
pierroz Avatar answered Nov 02 '22 03:11

pierroz