What's the difference between ref and type in an XML schema?

schema, xml, xsd

Solution

Using ref=".." you are "pasting" existing element/attribute defined on the other place. Using type=".." you are assigning some structure (defined in complextype/simpletype) to new element/attribute. Look at following:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tst="test" targetNamespace="test">

    <xs:complexType name="Root">
        <xs:sequence>
            <xs:element ref="tst:Child" />
            <xs:element name="Child2" type="tst:ChildType" />
        </xs:sequence>
        <xs:attribute ref="tst:AttRef" />
        <xs:attribute name="Att2" type="tst:AttType" />
    </xs:complexType>

    <xs:complexType name="ChildType">
        <xs:attribute ref="tst:AttRef" />
    </xs:complexType>

    <xs:element name="Child">
    </xs:element>

    <xs:simpleType name="AttType">
        <xs:restriction base="xs:string">
            <xs:maxLength value="10" />
        </xs:restriction>
    </xs:simpleType>

    <xs:attribute name="AttRef" type="xs:integer" />

</xs:schema> 

Problem

Consider the following schema: ``` <?xml version="1.0" encoding="ISO-8859-1" ?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="Root"> <xs:sequence> <xs:element ref="Child" /> <xs:element name="Child2" type="Child" /> </xs:sequence> <xs:attribute ref="Att" /> <xs:attribute name="Att2" type="Att" /> </xs:complexType> <xs:complexType name="Child"> <xs:attribute ref="Att" /> </xs:complexType> <xs:attribute name="Att" type="xs:integer" /> </xs:schema> ``` The `ref` to "Child" on line 6 fails, while the `type` on line 7 validates. For the attribute, the `ref` succeeds while the `type` fails. I'm trying to understand why. My understanding of `ref` was that it simply referred to another element and specified that you expect to see an instance of the referred type (with the name given in the definition) at that location. Obviously I'm wrong, so what does `ref` actually mean?

Original source