Search code examples
xmlxsd

XSD uniqueness constraint


I'm trying to generate an XSD for the below sample xml file. The idea is to generate this file and validate it as part of an automation.

<?xml version="1.0" encoding="UTF-8"?>
<CustomLabels
    xmlns="http://soap.sforce.com/2006/04/metadata">
    <labels>
        <fullName>Label1</fullName>
        <categories>L1</categories>
        <language>en_US</language>
        <protected>false</protected>
        <shortDescription>This is label 1</shortDescription>
        <value>1</value>
    </labels>
    <labels>
        <fullName>Label2</fullName>
        <categories>L2</categories>
        <language>en_US</language>
        <protected>false</protected>
        <shortDescription>Label 2 </shortDescription>
        <value>2</value>
    </labels>
        <labels>
        <fullName>Label2</fullName>
        <categories>L2</categories>
        <language>en_US</language>
        <protected>false</protected>
        <shortDescription>New label</shortDescription>
        <value>New value</value>
    </labels>
</CustomLabels>

The xsd I've generated so far is:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns="http://soap.sforce.com/2006/04/metadata"
           targetNamespace="http://soap.sforce.com/2006/04/metadata"
           elementFormDefault="qualified"
           attributeFormDefault="unqualified">

  <xs:element name="CustomLabels">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="labels">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="fullName" type="xs:string"/>
              <xs:element name="categories" type="xs:string" minOccurs="0"/>
              <xs:element name="language" type="xs:string"/>
              <xs:element name="protected" type="xs:boolean" minOccurs="0"/>
              <xs:element name="shortDescription" type="xs:string" minOccurs="0"/>
              <xs:element name="value" type="xs:string"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
    <xs:unique name="fullname_unique">
            <xs:selector xpath="labels/fullName"/>
            <xs:field xpath="."/>
    </xs:unique>
  </xs:element>
</xs:schema>

I've put a uniqueness check for fullName, however this doesn't seem to work somehow. Can someone explain what's the problem here and guide on how to acheive this?


Solution

  • Your elements are in a namespace and the XPath expressions need to reflect this. Use <xs:selector xpath="p:labels/p:fullName"/> and add xmlns:p="http://soap.sforce.com/2006/04/metadata" to the xs:schema element.