如何确保XML模式中的元素值是惟一的?

时间:2021-01-07 17:14:58

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

我想确保以下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.

oXygen XML编辑器告诉我当我验证时它是有效的。

Can anybody see what I am doing wrong?

有人能看出我做错了什么吗?

1 个解决方案

#1


11  

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

您可以尝试此站点来验证您的xml: http://www.xmlvalidation.com

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

您将看到它在xmldocument中发现错误:

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

重复唯一值[Book1]声明元素“books”的标识约束

#1


11  

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

您可以尝试此站点来验证您的xml: http://www.xmlvalidation.com

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

您将看到它在xmldocument中发现错误:

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

重复唯一值[Book1]声明元素“books”的标识约束