Reputation: 5419
Suppose I define an XML schema as follows. Consider a simple User element that has an id, name, email, age, and a set of other Users he/she is friends with. The friend element would simply hold the id of the User he/she is friends with. The XML would like something like:
<user>
<id>1</id>
<name>Alice</name>
...
<friend>2</friend>
<friend>3</friend>
</user>
I'm struggling to create the corresponding schema. I currently have the schema below, but because the schema for friend
is defined as such, I need to include all of the User element nested inside the <friend>
tag.... which is clearly a bad idea. How can I change my XML schema to allow for a foreign key reference to another User id?
Current schema:
<xsd:complexType name="userType">
<xsd:sequence>
<xsd:element name="id" type="xsd:int"></xsd:element>
[ ... many more fields ...]
<xsd:element name="friend" type="userType" minOccurs="0" maxOccurs="unbounded"></xsd:element>
</xsd:sequence>
</xsd:complexType>
Upvotes: 1
Views: 998
Reputation: 9391
If you are willing to allow generic names as ids (instead of integers only), you can take advantage of the ID,IDREF,IDREFS
definitions in XSD. Your schema would then look like this:
<xsd:complexType name="userType">
<xsd:sequence>
<xsd:element name="id" type="xsd:ID"/>
[ ... many more fields ...]
<xsd:element name="friend" type="xsd:IDREF" minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
However, since these types were originally defined only as attribute types, you may run into problems with certain XSD processors. A version optimized for compatibility and compactness would look like this:
<xsd:complexType name="userType">
<xsd:sequence>
[ ... many fields ...]
<xsd:element name="friends">
<xsd:complexType>
<xsd:attribute name="ids" type="xsd:IDREFS"/>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
<xsd:attribute name="id" type="xsd:ID"/>
</xsd:complexType>
The corresponding XML would be
<user id="1">
<name>Alice</name>
...
<friends ids="2 3"/>
</user>
Upvotes: 1