setting up xsd for key and validating the xml

34 Views Asked by At

I'm trying to set up an xsd for xml to, and make sure there are no duplicate child element value for an element. Below is an invalid xml example.

<NonSectorSpecific>
    <ElementTypes>
      <item>
        <Type>textarea</Type>
      </item>
      <item>
        <Type>select</Type>
      </item>
      <item>
        <Type>select</Type>
      </item>
    </ElementTypes>
  </NonSectorSpecific>

I have created and xsd which validates the schema correctly but cannot throw exception for having invalid key to the Type element.

<xs:schema
  targetNamespace="http://internal.gug.icmemo.com/test"
  elementFormDefault="qualified"
  xmlns="http://internal.gug.icmemo.com/test"
  xmlns:o="http://internal.gug.icmemo.com/test"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
  <xs:element name="Configuration">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="NonSectorSpecific">
          <xs:complexType>
            <xs:sequence>
              <xs:element ref="ElementTypes"  minOccurs="0" maxOccurs="unbounded"/>          
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
    <xs:unique  name="PKElementType">
      <xs:selector xpath="NonSectorSpecific/ElementTypes/item/Type"/>
      <xs:field xpath="."/>
    </xs:unique >
 </xs:element>  

  <xs:complexType name="ElementType">
    <xs:sequence>
      <xs:element name="Type" type="xs:string" />
    </xs:sequence>
  </xs:complexType>   
  <xs:element name="ElementTypes">
    <xs:complexType>
      <xs:sequence minOccurs="0" maxOccurs="unbounded">
        <xs:element name="item" type="ElementType"/>
      </xs:sequence>
    </xs:complexType>      
  </xs:element>  
</xs:schema>

I honestly have not worked with XMl in ages and can't seem to find a too many online documentations on dealing with keys at element values (and not to the attributes).

1

There are 1 best solutions below

0
Michael Kay On

You've defined the constraint on a Configuration element, but there is no Configuration element in the sample XML you posted. If you want to impose a constraint that no NonSectorSpecific element has two Type's with the same value, you need to define the constraint in the element declaration for NonSectorSpecific.

By the way, in my view by relying on "online documentations" you are working with one hand tied behind your back. The best information is found in books that you have to pay for: you're going to get much better information from an author who has spent six months to a year working out the best way to present the subject. I have two books on XSD, by Eric van der Vlist and by Priscilla Walmsley, and you would have no trouble finding the answer to this question in either.