Search code examples
xmlxsdxsd-validationxml-validation

Is it possible to allow any valid XML as a child of an element in an XSD?


I know the whole point of an XSD is to define the structure of the the XML, but is it possible to let a child be any valid XML? For example:

If I have this XSD

<xsd:complexType name="soExample">
  <xsd:all>
    <xsd:element name="field1" type="xsd:integer" />
  </xsd:all>
</xsd:complexType>

A valid XML is

<soExample>
  <field1>25</field1>
</soExample>

Now I want a special field field2 which allows me to put any XML that can be parsed inside, XSD would look like:

<xsd:complexType name="soExample">
  <xsd:all>
    <xsd:element name="field1" type="xsd:integer" />
    <xsd:element name="field2" type="so:special" />
  </xsd:all>
</xsd:complexType>

And a valid XML would be:

<soExample>
  <field1>25</field1>
  <field2>
    <anything>3</anything>
  </field2>
</soExample>

or

<soExample>
  <field1>25</field1>
  <field2>
    <cars>
      <favorite>"miata"</favorite>
    </cars>
  </field2>
</soExample>

I have a feeling this isn't possible because there's not a good way to resolve the types... but worth asking.


Solution

  • Yes, the purpose of xsd:any is to allow any XML at a given point in an XML document:

    <xsd:element name="field2"/>
      <xsd:complexType>
        <xsd:sequence>
          <xsd:any processContents="skip"/>
        </xsd:sequence>
      </xsd:complexType>
    </xsd:element>
    

    For an explanation of the various values supported for xsd:any/@processContents, see processContents strict vs lax vs skip for xsd:any.

    Note, you could also simply not specify the content model of field2:

    <xsd:element name="field2"/>
    

    See also XML Schema that allows anything (xsd:any).