tags:

views:

285

answers:

2

How would I define an element that can either contain plain text or contain elements? Say I wanted to somehow allow for both of these cases:

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

<xs:element name="field" type="xs:string" />

... so that both these elements would be valid:

<field name="test_field_0">
    <subfield>Some text.</subfield>
</field>

<field name="test_field_1">Some more text.</field>
+2  A: 

I did some research on this a while ago and the only solution I found was to used the mixed attribute:

<xs:element name="field">
    <xs:complexType mixed="true">
        <xs:sequence>
                <xs:element ref="subfield" minOccurs="0" maxOccurs="unbounded" />
        </xs:sequence>
        <xs:attribute name="name" type="xs:string" />
    </xs:complexType>
</xs:element>

This sadly also allows

<field name="test_field_0">
    Some text I'm sure you don't want.
    <subfield>Some text.</subfield>
    More text you don't want.
</field>

Hopefully someone will give a better answer.

David Norman
+1  A: 

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