Question

How should I reference another complexType in xml, as element or as attribute over my own defined Key? What is the correct approach to model the following self-reference? Is the first approach even possible, or does it lead to infinite self-referencing?

<xs:complexType name="Category">
  <xs:sequence>
    <xs:element name="ParentCategory" type="Category" minOccurs="1" maxOccurs="1"></xs:element>
    <xs:element name="ChildCategory" type="Category" minOccurs="0" maxOccurs="unbounded"></xs:element>
  </xs:sequence>
  <xs:attribute name="CategoryName" type="xs:string"></xs:attribute>
</xs:complexType>

or

<xs:complexType name="Category">
  <xs:sequence>
    <xs:element name="ChildCategory" type="Category" minOccurs="0" maxOccurs="unbounded"></xs:element>
  </xs:sequence>
  <xs:attribute name="CategoryName" type="xs:string"></xs:attribute>
  <xs:attribute name="ParentCategory" type="xs:string"></xs:attribute>
</xs:complexType>

I'm a bit confused - since I want to be object oriented, but am not sure how this would look like in XML. Wouldn't the reference of ParentCategory as a Category-type require me to again write a Category-type in XML that itself has a ParentCategory child-element, etc... leading to infinite type-referencing.

Was it helpful?

Solution

There's no issue referencing an element of the same type as part of the type definition, so your first example is fine from that point of view. Trying to reference the parent is a bit odd though, you shouldn't really need to do this... XML is hierarchical after all.

<xs:complexType name="Category">
  <xs:sequence>
    <xs:element maxOccurs="unbounded" minOccurs="0" name="ChildCategory" type="Category"/>
  </xs:sequence>
  <xs:attribute name="CategoryName" type="xs:string"/>
</xs:complexType>

The Category type references itself recursively, allowing for 0 or more ChildCategory elements. This should do what you need (there's nothing wrong with recursive type referencing in the XML Schema).

If you need to refer to the parent Category in your document, it's easy enough to chain to the parent node in any DOM implementation or with XPath.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top