Kas
Kas

Reputation: 21

How to require an element based on a 'type' attribute value?

I'm trying to build a XSD for the below XML and I'm using JAXB to unmarshal to Java Object with validation.

The validation rule is that the first 2 elements in <JobParam> which are type = jobType and type = customer are required. All others within JobParam are optional.

How do I create an XSD for this?

<job>
    <jobName>core</jobName>
    <jobParams>
         <jobParam type="jobType">Scheduler</jobParam>
         <jobParam type="customer">Alphabet</jobParam>
         <jobParam type="mode">music</jobParam>
      </jobParams>
</job>

Upvotes: 1

Views: 52

Answers (1)

kjhughes
kjhughes

Reputation: 111521

You cannot express your validation rule in XSD 1.0. You would have to do it in Java against your JAXB-created objects, or move to XSD 1.1 where you could use assertions or conditional type assignment.

However, the best solution would be to fix your XML design:

  • There's no need to repeat the parent name in the children's names. [minor]
  • If element types are a part of the name rather than an attribute value, simple XSD 1.0 occurrence constraints can be used to represent your validation rule. [major]

Here are the above improvements made to your XML:

<job>
    <name>core</name>
    <params>
         <type>Scheduler</type>
         <customer>Alphabet</customer>
         <mode>music</mode>
     </params>
</job>

Two other improvements you might consider:

  1. Drop the params wrapper, promoting its children to be children of job.
  2. Add back a customParams wrapper if you really must support parameters not known at XSD design time.

For example:

<job>
    <name>core</name>
    <type>Scheduler</type>
    <customer>Alphabet</customer>
    <customParams>
       <customParam type="mode">music</customParam>
    </customParams>
</job>

This can trivially be represented along with your validation rule regarding customer and mode via basic occurrence constraints in XSD 1.0.

Upvotes: 1

Related Questions