Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

xsd - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...