How to declare an attribute ID in XML

You should go back to using type="xsd:ID". What this does in addition to making sure that the value is unique is that it will also allow you to use xsd:IDREF for referencing.

The error you're getting when you try to use xsd:ID is that an ID value must start with a letter. If you change your ID's to something like "ID-1"/"ID-2" or "a1"/"a2", it will work fine.

Example Schema:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
  <xsd:element name="doc">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element maxOccurs="unbounded" ref="a"/>
        <xsd:element maxOccurs="unbounded" ref="b"/>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
  <xsd:element name="a">
    <xsd:complexType>
      <xsd:simpleContent>
        <xsd:extension base="xsd:string">
          <xsd:attribute name="id" use="required" type="xsd:ID"/>
        </xsd:extension>
      </xsd:simpleContent>
    </xsd:complexType>
  </xsd:element>
  <xsd:element name="b">
    <xsd:complexType>
      <xsd:simpleContent>
        <xsd:extension base="xsd:string">
          <xsd:attribute name="idref" use="required" type="xsd:IDREF"/>
        </xsd:extension>
      </xsd:simpleContent>
    </xsd:complexType>
  </xsd:element>
</xsd:schema>

Example XML:

<doc xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="Untitled1.xsd">
  <a id="ID-1">
    ...........
  </a>
  <a id="ID-2">
    ............
  </a>
  <b idref="ID-1"/>
</doc>

"1" is a valid string, so validation does not return an error. If you want to specify some restriction (e.g. "id should starts with a letter"), you have to declare your type and specify the pattern:

<xsd:simpleType name="myID">
    <xsd:restriction base="xsd:string">
        <xsd:pattern value="[a-zA-Z].*"/>
    </xsd:restriction>
</xsd:simpleType>
....
  <xsd:attribute name="id" type="myID"/>
....

If you want to specify the uniqueness restriction, you can use the xsd:unique element like this:

<xsd:element name="root" type="myList">
  <xsd:unique name="myId">
    <xsd:selector xpath="./a"/>
    <xsd:field xpath="@id"/>
  </xsd:unique>
</xsd:element> 

This will mean that element "root" declared as some "myList" should contain subelements "a" with unique attributes "id"

Tags:

Xml

Xsd