bentz123
bentz123

Reputation: 1121

Vary type in XSD according to element value?

I have the following two XML documents:

<struct>
<type>a</type>
<p1 xsi:nil="true"/>
<p2 xsi:nil="true"/>
</struct>

<struct>
<type>b</type>
<p1 xsi:nil="true"/>
<p2 xsi:nil="true"/>
</struct>

I wish to build a schema which validates that in case the value of the element type is "a", then it's sub elements (aka p1 & p2) should be nil or empty. Whereas when the element type is something else, such as "b", then p1 or p2 elements can contain anything or nothing.

Upvotes: 2

Views: 100

Answers (2)

Michael Kay
Michael Kay

Reputation: 163585

That's a classic example of a "co-occurrence constraint" (the type of one element depends on the value of another). This can't be done with XSD 1.0, but it can be done using XSD 1.1 by means of assertions

<xs:assert test="if (type eq 'a') then nilled(p1) else true()"/> 

Upvotes: 2

kjhughes
kjhughes

Reputation: 111726

Your XML design is non-ideal.

An element shouldn't be named as generically as struct if you want to further constrain its contents.

Instead of

<struct>
  <type>a</type>
  <p1/>
  <p2/>
</struct>

use

<a>
  <p1/>
  <p2/>
</a>

and you'll have no problems writing the XSD.

If you insist on the former form, you'll have to use XSD 1.1's assertion facilities. You can find many examples on this site (or even within an answer just added to this question) of how to write assertions that restrict one element or elements based upon the value of another element.

See also:

Upvotes: 1

Related Questions