XML Schema:可以包含元素或文本的元素?

时间:2008-12-19 18:27:03

标签: xml xsd

如何定义可以包含纯文本或包含元素的元素?说我想以某种方式允许这两种情况:

<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" />

...以便这两个元素都有效:

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

<field name="test_field_1">Some more text.</field>

2 个答案:

答案 0 :(得分:24)

我刚才做了一些研究,我找到的唯一解决方案是使用混合属性:

<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>

这也很遗憾地允许

<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>

希望有人会给出更好的答案。

答案 1 :(得分:13)

另一种选择是使用继承。您生成的XML不是很漂亮,但您可以获得所需的内容:

<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>

然后您生成的XML将包含以下内容(假设您已在某处声明xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

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

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

最重要的是,它不允许

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