How to declare an attribute identifier in XML

I write XML and XSD as a destination ... In my XML, I have a tag (not the actual name) and an id attribute. Part of my XML is shown below:

  <a id="1"> ........... </a> <a id="1"> ............ </a> 

When I check the use of XSD, it does not give an error ....

  <xsd:attribute name="id" type="xsd:string" /> 

I tried using xsd: ID as the id attribute data type, but it gave me an error; I could not understand what the problem was.

How can i do this?

+7
source share
2 answers

You should return to using type="xsd:ID" . What this does in addition to ensuring that the value is unique is that it also allows you to use xsd:IDREF for links.

The error you get when you try to use xsd:ID is that the identifier value must begin with a letter. If you change your ID to "ID-1" / "ID-2" or "a1" / "a2", it will work fine.

Example circuit:

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

XML example:

 <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> 
+14
source

"1" is a valid string, so the check does not return an error. If you want to specify some kind of restriction (for example, "id must begin with a letter"), you must declare your type and specify a 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 a unique constraint, you can use the xsd: unique element as follows:

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

This means that the root element declared as some kind of "myList" must contain subelements "a" with unique attributes "id"

+1
source

All Articles