XSD <any>Element


The <any> element enables us to extend XML documents with elements not specified by the schema!


<any> Element

The <any> element enables us to extend XML documents with elements not specified by the schema!

The following example is a fragment taken from the XML schema named "family.xsd". It shows a declaration for the "person" element. By using the <any> element, we can extend the content of "person" with any element (after <lastname>):

<xs:element name="person">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="firstname" type="xs:string"/>
      <xs:element name="lastname" type="xs:string"/>
      <xs:any minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

Now, we want to extend the "person" element with the "children" element. In this case, we can do so, even though the author of the above schema did not declare any "children" element.

Please look at this schema file, named "children.xsd":

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

<xs:element name="children">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="childname" type="xs:string"
      maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

</xs:schema>

The following XML file (named "Myfamily.xml") uses elements from two different schemas, "family.xsd" and "children.xsd":

<?xml version="1.0" encoding="ISO-8859-1"?>

<persons xmlns="http://www.microsoft.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.microsoft.com family.xsd
http://www.w3schools.com children.xsd">

<person>
  <firstname>Hege</firstname>
  <lastname>Refsnes</lastname>
  <children>
    <childname>Cecilie</childname>
  </children>
</person>

<person>
  <firstname>Stale</firstname>
  <lastname>Refsnes</lastname>
</person>

</persons>

The above XML file is valid because the schema "family.xsd" allows us to extend the "person" element with optional elements after the "lastname" element.

Both <any> and <anyAttribute> can be used to make extensible documents! They give documents the ability to contain additional elements that were not declared in the primary XML schema.

Other Extensions