Re: constraining an element to be either simple or complex content

Hi Dolan,

> > For example: <X>23</X> is valid and <X><Y>45</Y></X> is also valid
> > but not <X>23<Y>45</Y></X>. Use of a "mixed" content model permits
> > the first two cases but does not exclude the last one.
>
> You could go this route and add a schema adjunct (some RELAX NG or
> Schematron elements in xs:appinfo) that went on to define more tightly
> that the X element can either have text or a Y element as a child. Of
> course you would have to pull out these extra constraints yourself in
> order to test them, but they'd be there in the schema for
> documentation purposes.

If you choose to go with the Schematron option this is one way to do it:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified" attributeFormDefault="unqualified">
 <xs:element name="X">
  <xs:annotation>
   <xs:appinfo>
    <pattern name="Restrict mixed content"
xmlns="http://www.ascc.net/xml/schematron">
     <rule context="X[count(*)=0]">
      <assert test='(text() != "")'>If you don't have a Y element you must
store the value in the X element.</assert>
     </rule>
     <rule context="X[Y]">
      <assert test="string-length(text()) = 0">If you have a Y element you
can't have text content in the X element.</assert>
     </rule>
    </pattern>
   </xs:appinfo>
  </xs:annotation>
  <xs:complexType mixed="true">
   <xs:sequence>
    <xs:element name="Y" type="xs:integer" minOccurs="0"/>
   </xs:sequence>
  </xs:complexType>
 </xs:element>
</xs:schema>

The Schematron Validator from Topologi [1] can validate XML Schemas and
Schematron as well as provide validation results from embedded Schematron
rules like the above example. For more information about Schematron see
[2] and more information about how to extend XML Schemas can be found at
[3].

Cheers,
/Eddie

[1] www.topologi.com
[2] http://www.ascc.net/xml/resource/schematron/
[3] http://www.xfront.com/BestPracticesHomepage.html (see Extending XML
Schemas)

Received on Monday, 22 October 2001 20:15:48 UTC