We help IT Professionals succeed at work.

XSD Conditional Elements

CodeMarx
CodeMarx asked
on
I need to make some elements required based on the value of another element.

<xs:element name="LoanType" type="xs:string" />
If LoanType is Adjustable then
<xs:element name="Margin" type="xs:int" />
else
<xs:element name="Margin" type="xs:int" minOccurs="0' />

Thanks in advance.
Comment
Watch Question

Gertone (Geert Bormans)Information Architect
CERTIFIED EXPERT
Top Expert 2006

Commented:
You can't achieve this by simply XSD.
What you are asking for is a co-occurence constraint, a type of constraint that can not be modelled by XSD schema.
You basically have three options
- have a second schema that uses schematron constraints (http://www.schematron.com/)
- use an XSD parser that allows embedded schematron rules (this would be the approach I would use)
- use an XSD parser that understands XSD 1.1, a new schema evolution that has "assert", very similar to schematron assertions

Author

Commented:
How about applying a XLST to the XML document first?
Information Architect
CERTIFIED EXPERT
Top Expert 2006
Commented:
well, using XSLT for validation... in a sence that is what schematron does (most implementations transform the schematron schema in a reporting XSLT)
schematron gives you the comfort of embedding in a schema and standardized reporting
(from the point of view of the application, schematron is a standardized constraint language, XSLT is code,
so if you need users to change the rules later, I would prefer schematron)
On the other hand XSLT can do both reporting or twiddling the XML to fit the XSD schema
I use both techniques a lot (XSLT for reporting validation errors and XSLT for twiddling an XML to fit an XSD)
So yes, it can definitely be done, and would be an option here

Commented:
One defines a complecType called LoansType, which is a choice of various loan types (elements). One such element is called AdjustableLoanType which then can have Margin as either a sub-element or an attribute.

Generally if you have an enumeration which causes structural differences then you should enumerate the structures rather than use a scalar and overload the structure.