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

三世轮回 提交于 2019-11-28 02:35:02

问题


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?


回答1:


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"



来源:https://stackoverflow.com/questions/2386633/how-do-i-ensure-unique-element-values-in-an-xml-schema

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!