XSD anyAttribute Element

To extend the XML document with attributes not specified by the schema, the <anyAttribute> element is used.

The <anyAttribute> Element:

To make EXTENSIBLE documents, i.e., to allow documents to contain additional elements that are not declared in the main XML schema, the <any> and <anyAttribute> elements are used.

Example:

<xs:element name="student">
  <xs:complextype>
    <xs:sequence>
      <xs:element name="firstname" type="xs:string"></xs:element>
      <xs:element name="lastname" type="xs:string"></xs:element>
    </xs:sequence>
    <xs:anyattribute></xs:anyattribute>
  </xs:complextype>
</xs:element>

Explanation:

In the above example, we are displaying a fragment from an XML schema called “friend.xsd”, declaring the “student” element. The number of attributes to the “student” element can be increased by using the <anyAttribute> element.

attribute.xsd:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="https://www.w3spoint.com"
xmlns="https://www.w3spoint.com"
elementFormDefault="qualified">
 
<xs:attribute name="dresscolor">
  <xs:simpletype>
    <xs:restriction base="xs:string">
      <xs:pattern value="blue|green|red|yellow"></xs:pattern>
    </xs:restriction>
  </xs:simpletype>
</xs:attribute>
 
</xs:schema>

Explanation:

In the above example, we are extending the “student” element with the “dresscolor” attribute, even when the author of the above schema never declared any “dresscolor” attribute.

Example:

<?xml version="1.0" encoding="UTF-8"?>
 
<students xmlns="http://www.microsoft.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:SchemaLocation="http://www.microsoft.com friend.xsd
https://www.w3spoint.com attribute.xsd">
 
<student dresscolor="red">
  <firstname>Tom</firstname>
  <lastname>Jonas</lastname>
</student>
 
<student dresscolor="yellow">
  <firstname>Jack</firstname>
  <lastname>Davis</lastname>
</student>
 
</students>

Explanation:

In the above example, we are creating the “Myfriend.xml” file to use the components from two different schemas; “friend.xsd” and “attribute.xsd”. Now, since the schema “friend.xsd” allows us to add an attribute to the “student” element, the XML file Myfriend.xml is valid.

Please Share