【问题标题】:keyref in xsd not workingxsd中的keyref不起作用
【发布时间】:2015-12-28 14:54:49
【问题描述】:

下面是我的 xsd 和 xml 的简化版本。 我正在尝试检查每个 OrderedPart@rPartId 在 Part@PartId 中是否有有效匹配。

我尝试过的所有工具都告诉我这个 XML 对这个 xsd 有效。 但是第二个订单应该给出错误,因为 67 不是有效的 Part@PartId。

XSD

<?xml version="1.0" encoding="UTF-8"?>

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://localhost" xmlns="http://localhost" targetNamespace="http://localhost" elementFormDefault="qualified" attributeFormDefault="unqualified" >

    <xs:element name="root">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="Order" type="OrderType" maxOccurs="unbounded"/>
            <xs:element name="Parts" type="PartType"/>
        </xs:sequence>
    </xs:complexType>

    <xs:keyref name="dummy" refer="pNumKey">
        <xs:selector xpath="tns:OrderedPart" />
        <xs:field xpath="@rPartId"/>
    </xs:keyref>

    <xs:key name="pNumKey">
        <xs:selector xpath="tns:Part"/>
        <xs:field xpath="@PartId"/>
    </xs:key>
</xs:element>

<xs:complexType name="OrderType">
    <xs:sequence>
      <xs:element name="OrderedPart" maxOccurs="unbounded">
          <xs:complexType>
              <xs:attribute name="rPartId" type="xs:integer"/>
          </xs:complexType>
      </xs:element>
  </xs:sequence>
</xs:complexType>

<xs:complexType name="PartType">
    <xs:sequence>
      <xs:element name="Part" maxOccurs="unbounded">
          <xs:complexType>
              <xs:attribute name="PartId" type="xs:integer"/>
          </xs:complexType>
      </xs:element>
  </xs:sequence>
</xs:complexType>
</xs:schema>

和 XML:

<?xml version="1.0" encoding="UTF-8" ?>

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:noNamespaceSchemaLocation="KeyRefs.xsd"  xmlns="http://localhost" >
<Order>
    <OrderedPart rPartId="1"/>
</Order>
<Order>
    <OrderedPart rPartId="67"/> <!-- validation should give error -->
</Order>
<Parts>
    <Part PartId="1"/>
</Parts>
</root>

怀疑它与选择器中的 xPath 和/或命名空间有关。 根据本网站上其他帖子的输入,我使用了命名空间组合,但无法使其正常工作。

欢迎任何建议。

(作为 OP 的更新似乎丢失了一些 XSD)

【问题讨论】:

  • 似乎丢失了 xsd 的开始:

标签: xml validation xpath xsd


【解决方案1】:

XSD 的主要问题是您没有正确使用选择器。 选择器相对于它们所属的元素,正如XSD specs中所说:

{selector} 指定一个受限的 XPath ([XPath]) 表达式相对 到被声明的元素的实例。

因此,您需要将 xpath 选择器更改为 tns:Order/tns:OrderedParttns:Parts/tns:Part 以选择正确的元素。

此外,您使用PartId 属性作为键,但它被定义为可选属性。通常这不是所期望的行为,因为如果密钥不存在,则会出现错误,因此您可以在属性中使用use="required"

【讨论】:

  • 你是对的。对选择器进行描述的更改修复了该问题。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-02
  • 1970-01-01
  • 2010-10-27
相关资源
最近更新 更多