1

We have a situation where we want to restrict an element to having:

  • Either text(). or
  • Subelements.

E.g.

<a>mytext</a>

or

<a><b>xxx</b></a>

But not:

<a>mytext<b>xxx</b></a>

Given the xs:simpleContent mechanism I can restrict it to having only text, and of course I can define the element(s) it can be allowed, but does anyone know how I can combine the two to allow either text or subelements but not both?

Ta Jamie

Community
  • 1
  • 1
Jamie Love
  • 5,418
  • 6
  • 30
  • 33
  • 2
    Exactly this questions was asked at: http://stackoverflow.com/questions/381782/xml-schema-element-that-can-contain-elements-or-text. Not sure how I missed it! Vote to close if you like. – Jamie Love Jun 25 '09 at 01:38

1 Answers1

3

Another option is for you to use inheritance. Your resulting XML isn't as pretty, but you get exactly the content you want:

<xsd:element name="field" type="field" abstract="true" />
<xsd:element name="subfield" type="xsd:string" /> 

<xsd:complexType name="field" abstract="true" />

<xsd:complexType name="subfield">
  <xsd:complexContent>
    <xsd:extension base="field">
      <xsd:sequence>
        <xsd:element ref="subfield" minOccurs="0" maxOccurs="unbounded" />
      </xsd:sequence>
      <xsd:attribute name="name" type="xsd:string" />
    </xsd:extension>
  </xsd:complexContent>
</xsd:complexType>

<xsd:complexType name="no-subfield">
  <xsd:complexContent mixed="true">
    <xsd:extension base="field">
      <xsd:attribute name="name" type="xsd:string" />
    </xsd:extension>
  </xsd:complexContent>
</xsd:complexType>

Then your resulting XML would contain the following (assuming you have xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" declared somewhere)

<field xsi:type="subfield">
  <subfield>your stuff here</subfield>
</field>

or

<field xsi:type="no-subfield">your other stuff</field>

Most importantly, it disallows

<field xsi:type="subfield">
  Text you don't want
  <subfield>your stuff here</subfield>
  More text you don't want
</field>
barkimedes
  • 331
  • 3
  • 8