xsd唯一约束不起作用

时间:2014-03-12 13:38:32

标签: xml xsd

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

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

我们一直在奋斗......天。谢谢你找到了。

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>

1 个答案:

答案 0 :(得分:8)

架构中存在两个问题:

第一个是您的选择器XPath不正确,具体取决于您定义它的位置。 <xs:unique>元素 <Inserts>元素中,但您的XPath读取Inserts/Insert,意味着在<Inserts>元素中,另一个<Inserts>元素} element是预期的,只有<Insert>元素。

<xs:unique>约束已经在<Inserts>元素中,这就是您只需找到<Insert>元素的原因:

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

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

要处理这个问题,请为您的命名空间添加名称空间前缀(作为默认名称空间的替代方法)到XSD文件中:

  <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中使用该命名空间前缀:

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

通过这些更改,this validator输出

  

http://www.osames.org/osamesorm:unique-isbn”键或唯一标识约束存在重复的键序列“BaseInsert”。行:1列:357