fidel150992
fidel150992

Reputation: 303

Can't make unique constraint for attribute in xml

I have xml file like below:

<?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>

And I need to make attribute id of State element unique in element StateContentMappings. I have used xsd like below:

<?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>

But for some reason it doesn't work in my case(I have used Eclipse editor for checking vakidation).

Upvotes: 0

Views: 72

Answers (1)

dcsohl
dcsohl

Reputation: 7396

It seems to me that your selector element is looking for State elements that are direct children of StateContentMappings, and there are none.

Try using

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

Upvotes: 1

Related Questions