Monday, October 3, 2016

XML Schema 1.1 : overlap in concept of CTA and "assert"

Here's another example, where I thought Conditional Type Alternative would have worked. It cannot in this case, because we have an attribute on element "X" and the data type is simple. Therefore we have to use an <assert> to solve this (because there's lot of conditional stuff here, an use case of XPath 2.0 "if", and a straight forward case of co-occurrence constraints).

Two valid XMLs:

(for attribute value 1, the simple type content of element "X" must be even)
<?xml version="1.0" encoding="UTF-8"?>
<X xa="1">

(for attribute value 2, the simple type content of element "X" must be odd)
<?xml version="1.0" encoding="UTF-8"?>
<X xa="2">

Invalid XML (attribute value other than 1 or 2 is not allowed):
<?xml version="1.0" encoding="UTF-8"?>
<X xa="3">

The XML Schema 1.1 solution is below:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="">

   <xs:element name="X">
            <xs:extension base="xs:int">
               <xs:attribute name="xa" type="xs:int"/>
               <xs:assert test="if (@xa = 1) then $value mod 2 = 0
                            else if (@xa = 2) then $value mod 2 = 1
                                else false()"/>

I hope this example is helpful.

No comments: