在同一XPath下的元素内限制元素的值是唯一的

时间:2010-02-25 20:51:10

标签: xml xsd

考虑这个XML -

<Root>
  <Foo>
    <UniqueValue>A100</UniqueValue>
  </Foo>
  <Foo>
    <UniqueValue>A101</UniqueValue>
  </Foo>
  <Foo>
    <UniqueValue>B102</UniqueValue>
  </Foo>
  <Foo>
    <UniqueValue>A101</UniqueValue> <!-- This should be an error -->
  </Foo>
  <Foo>
    <UniqueValue> A101 </UniqueValue> <!-- This should be an error but not critical for now -->
  </Foo>
</Root>

如何限制简单类型元素<UniqueValue>,使其值唯一? 也不是说我不想限制数字。

1 个答案:

答案 0 :(得分:2)

尝试在“Root”上添加唯一性约束。请注意,这需要是元素定义,而不是类型定义:

<xsd:element name="Root" type="RootType">
  <xsd:unique name="uniqueValues">
    <xsd:selector xpath="Foo"/>
    <xsd:field xpath="UniqueValue"/>
  </xsd:unique>
</xsd:element>

根据您使用的解析器,您可能必须打开其他选项才能进行此验证(例如“完整架构验证”,身份约束验证等)。