1

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?

kjhughes
  • 106,133
  • 27
  • 181
  • 240
Rahul Khimasia
  • 473
  • 12
  • 24

2 Answers2

1

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>
kjhughes
  • 106,133
  • 27
  • 181
  • 240
1

Global attributes are in fact very rarely used. One reason for this is that they are necessarily in the target namespace of the defining schema document, which is often not what you want. A popular alternative if you have attributes that are common to many elements is to define a global attributeSet (even if it only contains one attribute), because the attributes can then be in no namespace.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164