如何确保 XML 架构中的唯一元素值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2386633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 13:00:25  来源:igfitidea点击:

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

xmlxsdschemaoxygenxml

提问by Nick Miller

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?

谁能看到我做错了什么?

采纳答案by PierrOz

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"

为元素“books”的身份约束声明的重复唯一值 [Book1]