无法对xml中的属性进行唯一约束

时间:2016-10-06 14:23:27

标签: xml xsd xsd-validation

我有xml文件,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<ROOT xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="status_content_mapping.xsd">
    <StateContentMappings>
        <StateContentMapping>
            <State id="1" name="main" />
            <Content id="2" />
        </StateContentMapping>

        <StateContentMapping>
            <State id="3" name="sign on" />
            <Content id="1" />
        </StateContentMapping>

        <StateContentMapping>
            <State id="3" name="sign on" />
            <Content id="1" />
        </StateContentMapping>

        <StateContentMapping>
            <State id="3" name="sign on" />
            <Content id="1" />
        </StateContentMapping>
    </StateContentMappings>

</ROOT>

我需要在元素id中使State元素的属性StateContentMappings唯一。我使用过如下的xsd:

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

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="ROOT" type="RootType"/>

  <xs:complexType name="RootType">
    <xs:sequence>
      <xs:element name="StateContentMappings" type="StateContentMappingsType" minOccurs="0">
        <xs:unique name="StateIdIsUnique">
            <xs:selector xpath="State" />
            <xs:field xpath="@id" />
        </xs:unique>
      </xs:element>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="StateContentMappingsType">
    <xs:sequence>
      <xs:element name="StateContentMapping" type="StateContentMappingType" minOccurs="1" maxOccurs="unbounded" />
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="StateContentMappingType">
      <xs:sequence>
        <xs:element name="State" type="StateType" minOccurs="1" maxOccurs="1" />
        <xs:element name="Content" type="ContentType" minOccurs="1" maxOccurs="1" />
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="StateType">
    <xs:attribute name="id" type="xs:int" use="required" />
    <xs:attribute name="name" type="xs:string" use="required" />
  </xs:complexType>

  <xs:complexType name="ContentType">
    <xs:attribute name="id" type="xs:int" use="required" />
  </xs:complexType>

</xs:schema>

但由于某些原因它在我的情况下不起作用(我使用Eclipse编辑器来检查vakidation)。

1 个答案:

答案 0 :(得分:1)

在我看来,你的选择元素正在寻找State的直接子节点的StateContentMappings元素,而且没有。

尝试使用

    <xs:unique name="StateIdIsUnique">
        <xs:selector xpath="StateContentMapping/State" />
        <xs:field xpath="@id" />
    </xs:unique>