xmlxsdxsd-validationxml-validationschema-design

Purpose of defining an attribute globally in XSD


In XSD it is possible to define an attribute right under the schema element, like I have defined someAttr in the XSD below:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema targetNamespace="http://www.example.com"
           xmlns:xs="http://www.w3.org/2001/XMLSchema" 
           elementFormDefault="qualified" 
           attributeFormDefault="unqualified">
    <xs:element name="Companys">
        <xs:annotation>
            <xs:documentation>Comment describing your root element</xs:documentation>
        </xs:annotation>
        <xs:complexType>
            <xs:sequence>
                <xs:element name="Company" maxOccurs="unbounded">
                    <xs:complexType>
                        <xs:attribute name="companyname" type="xs:string" default="test1"/>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
    <xs:attribute name="someAttr" type="xs:string" default="R"/>
</xs:schema>

How would you use it?


Solution

  • You would use it via xs:attribute/@ref, which is particularly handy to allow one definition of someAttr to be used in multiple locations.

    XSD

    <?xml version="1.0" encoding="UTF-8"?>
    <xs:schema targetNamespace="http://www.example.com"
               xmlns:e="http://www.example.com"
               xmlns:xs="http://www.w3.org/2001/XMLSchema"
               elementFormDefault="qualified"
               attributeFormDefault="unqualified">
      <xs:element name="Companys">
        <xs:annotation>
          <xs:documentation>Comment describing your root element</xs:documentation>
        </xs:annotation>
        <xs:complexType>
          <xs:sequence>
            <xs:element name="Company" maxOccurs="unbounded">
              <xs:complexType>
                <xs:attribute name="companyname" type="xs:string" default="test1"/>
                <xs:attribute ref="e:someAttr"/>
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:attribute name="someAttr" type="xs:string" default="R"/>
    </xs:schema>