Yanqing Zhou
Yanqing Zhou

Reputation: 5

XML Schema (XSD) element with enumeration and child element

I am trying to write XML Schema (XSD) for XML checking. There is an element that contains an enumeration value and child element. Its format is really odd but accepted by xml.

Can a XML element contain text and child elements at the same time?

my case:

<tree>
    <node> enumeration Text (Text only allows "a", "b" and "c")
        <subnode1 attribute1="xx"> optional text1 </subnode1>
    </node1>
</tree>

I am trying to write the xml schema (XSD) to verify the format. The required element, node1, has Text with three restricted values. It will also contain a subnode1 inside it when the value of text equal to "c".

For example, the schema will pass the following cases:

<node1>a</node1>

or

<node1>b</node1>

or

<node1>c
    <subnode1 attribute1="1">what ever you what</subnode1>
</node1>

how ever, it won't pass:

<node1>d</node1>

or

<node1>c</node1>

becase subnode1 is neccessary for the value "c"

How can I write the XML Schema element with an enumeration and child element?

Upvotes: 0

Views: 661

Answers (1)

Michael Kay
Michael Kay

Reputation: 163342

No, XSD 1.0 doesn't support this. If an element allows mixed content (that is, both text and element children) then there is no way of constraining the text.

In XSD 1.1 you could define the constraints using assertions.

XSD is a bit paternalistic: it tries to support validation of the kind of XML that it thinks people ought to be designing. It takes a view (as does XSLT) that mixed content is there to enable marked-up narrative text, for example paragraphs in which some words are tagged as bold or italic. Your structure doesn't fit this model: the "approved" way to design your XML structure would be to put the enumeration value in an attribute. (Even then, you need XSD 1.1 conditional type assignment to make the type of the element's content contingent on the value of its attributes).

Upvotes: 1

Related Questions