Thursday, February 24, 2022

XML Schema 1.1 : <assertion> facet with attribute "fixed"

I've come up with an XML Schema 1.1 example, involving XSD <assertion> facet and XSD attribute "fixed", that I thought should be interesting to write about.

Please consider, following two XML instance documents,

XML document 1:
<?xml version="1.0"?>
<Test>
    <A>a</A>
    <country>USA</country>
    <C>c</C>
</Test>

XML document 2:
<?xml version="1.0"?>
<Test>
    <A>a</A>
    <country>U S A</country>
    <C>c</C>
</Test>

According to "XML document 1" specified above, the element "country" needs to have a fixed value "USA". Whereas, according to "XML document 2" specified above, the element "country" needs to have a fixed value USA with any amount of whitespace characters anywhere within the string value.

The XSD 1.1 schema, for "XML document 1" is following (the schema specified below, is a valid XSD 1.0 schema as well),

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    
    <xs:element name="Test" type="TestType" />
   
    <xs:complexType name="TestType">
        <xs:sequence>
            <xs:element name="A" type="xs:string"/>
            <xs:element name="country" type="xs:string" fixed="USA"/>            
            <xs:element name="C" type="xs:string"/>
        </xs:sequence>
    </xs:complexType>

</xs:schema>

Whereas, XSD 1.1 schema, for "XML document 2" is following,

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    
    <xs:element name="Test" type="TestType" />
   
    <xs:complexType name="TestType">
        <xs:sequence>
            <xs:element name="A" type="xs:string"/>
            <xs:element name="country">
               <xs:simpleType>
                  <xs:restriction base="xs:string">
                    <xs:assertion test="replace($value, '\s', '') = 'USA'"/>
                  </xs:restriction>
               </xs:simpleType>
            </xs:element>
            <xs:element name="C" type="xs:string"/>
        </xs:sequence>
    </xs:complexType>

</xs:schema>

According to the latter schema specified above, the XSD 1.1 <assertion> facet lets us achieve, a special notion of a fixed value as illustrated by the mentioned example above.

No comments: