我有一个根插入标签,一系列插入标签,每个标签都有一个“名称”属性。

我无法让在线验证器发现重复的“名称”值。

我们已经奋斗了……天。感谢您的发现。

XSD:

   <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://www.osames.org/osamesorm"
  targetNamespace="http://www.osames.org/osamesorm" elementFormDefault="qualified">

  <xs:element name="Inserts">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="Insert" maxOccurs="unbounded">
              <xs:complexType>
               <xs:simpleContent>
                  <xs:extension base="xs:string">
                    <xs:attribute name="name" type="xs:string" use="required"/>
                  </xs:extension>
                </xs:simpleContent>
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
        <xs:unique name="unique-isbn">
          <xs:selector xpath="Inserts/Insert"/>
          <xs:field xpath="@name"/>
        </xs:unique>
      </xs:element>

</xs:schema>

XML:
<?xml version="1.0" encoding="UTF-8"?>
<Inserts xmlns="http://www.osames.org/osamesorm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.osames.org/osamesorm ./xml_schemas/verysimple.xsd">
<Insert name="BaseInsert">INSERT INTO {0} ({1}) values ({2});</Insert>
<Insert name="BaseInsert">INSERT INTO {0} ({1}) values ({2});</Insert>
</Inserts>

最佳答案

模式中存在两个问题:

第一个是根据您定义选择器的位置,选择器XPath不正确。 <xs:unique>元素在<Inserts>元素内,但是您的XPath读取Inserts/Insert,这意味着在该<Inserts>元素内,需要另一个<Inserts>元素,并且仅在其中<Insert>元素。

但是,<xs:unique>约束已经在<Inserts>元素内,这就是为什么您只需要查找<Insert>元素的原因:

<xs:unique name="unique-isbn">
  <xs:selector xpath="Insert"/>
  <xs:field xpath="@name"/>
</xs:unique>

第二个问题是XPath没有使用xmlns属性在Xml中定义的默认 namespace 的概念。您在XPath中引用的Insert元素不是XSD的默认命名空间中的Insert元素,而是没有命名空间URI的Insert元素。

为了解决这个问题,请在XSD文件中为您的 namespace 添加 namespace 前缀(作为默认 namespace 的替代方法):
  <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://www.osames.org/osamesorm" targetNamespace="http://www.osames.org/osamesorm" xmlns:o="http://www.osames.org/osamesorm" elementFormDefault="qualified">

然后,在XPath中使用该 namespace 前缀:
<xs:unique name="unique-isbn">
  <xs:selector xpath="o:Insert"/>
  <xs:field xpath="@name"/>
</xs:unique>

通过这些更改,this validator输出

关于xml - xsd唯一约束不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22353302/

10-09 05:53