What does the ref attribute on an element in an XSD do?

XmlXsdSchema

Xml Problem Overview


Documentation seems to say that it references another element in the schema, but how could it be used - I've never seen it in schemas that I have worked with.

Anyone got any nice use cases or something that could explain its use further?

Xml Solutions


Solution 1 - Xml

Basically it references another element that is declared elsewhere, which may or may not be the same schema document.

For instance, it could come from an externally referenced schema in a different namespace. Suppose you use the item element a lot in several different schemas, you can declare it (and any other common types and attributes) in a common schema, and then reuse those in all your other schemas.

If you reference your common schema with the namespace c, you can declare an instance of the item element on its own or as part of a type as follows:

<xs:element ref="c:item" /><!-- reference here -->
<xs:complexType name="something">
    <xs:sequence>
        <xs:element ref="c:item" /><!-- and here -->
    </xs:sequence>
    <xs:element name="other" type="xs:Name" />
</xs:complexType>

The definition in the data schema would look like this:

<xs:element name="item" type="itemType" /><!-- referenced element -->
<xs:complexType name="itemType">
    <xs:sequence>
        <xs:element name="code" type="xs:Name" minOccurs="0" maxOccurs="unbounded" />
    </xs:sequence>
    <xs:attribute name="description" type="xs:normalizedString" use="required" />
</xs:complexType>

Solution 2 - Xml

For example if you want to declare element types that can appear deeply nested, but also as top level elements in an instance document.

The XML Schema Primer has examples for this: http://www.w3.org/TR/xmlschema-0/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFiona - myaccessible.websiteView Question on Stackoverflow
Solution 1 - XmlgrkvltView Answer on Stackoverflow
Solution 2 - XmlzedooView Answer on Stackoverflow