XSD <any> Element

The <any> element gives us the ability to extend an XML document with elements not specified by the schema!

The <any> element

The <any> element gives us the ability to extend an XML document with elements not specified by the schema!

The following example is a fragment from an 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 hope to use the "children" element to expand the "person" element. In this case, we can do so even if the author of this schema has not declared any "children" elements.

Please see 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.codew3c.com"
xmlns="http://www.codew3c.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 components 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.codew3c.com children.xsd">
<person>
<firstname>David</firstname>
<lastname>Smith</lastname>
<children>
  <childname>mike</childname>
</children>
</person>
<person>
<firstname>Tony</firstname>
<lastname>Smith</lastname>
</person>
</persons>

This XML file is valid because the schema "family.xsd" allows us to extend the "person" element by adding optional elements after the "lastname" element.

<any> and <anyAttribute> can both be used to create extensible documents! They enable documents to include additional elements that are not declared in the main XML schema.