0
votes

I would like to have rules embedded within my XSD schema definition for how optional attributes of an element are to be used. Consider the following element definition:

<xs:complexType name="sampleElement">
  <xs:attribute name="name" type="xs:string" use="required"/>
  <xs:attribute name="description" type="xs:string" use="optional"/>
  <xs:attribute name="optPrimary" type="xs:string" use="optional"/>
  <xs:attribute name="optSecondary" type="xs:string" use="optional"/>
</xs:complexType

In this example, both optPrimary and optSecondary are indeed optional. The attribute optPrimary can be used by itself, but optSecondary must be used in conjunction with optPrimary. Therefore, I would like a rule embedded in the schema that can be enforced when the XML is validated.

I have found examples of Schematron used for this in a separate file, but I have not found how it can be embedded as part of the schema.

1
XML schema does not support the ability to create constraints between elements. You have correctly identified schematron which addresses this gap. - Mark O'Connor

1 Answers

0
votes

XSD 1.1 supports this. This is one way of expressing it:

<?xml version="1.0" encoding="utf-8" ?>
<!-- XML Schema generated by QTAssistant/XSD Module (http://www.paschidev.com) -->
<xsd:schema targetNamespace="http://tempuri.org/XMLSchema.xsd" xmlns="http://tempuri.org/XMLSchema.xsd" elementFormDefault="qualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xerces="http://xerces.apache.org">
    <xsd:element name="sampleElement">
        <xsd:complexType>
            <xsd:attribute name="name" type="xsd:string" use="required"/>
            <xsd:attribute name="description" type="xsd:string" use="optional"/>
            <xsd:attribute name="optPrimary" type="xsd:string" use="optional"/>
            <xsd:attribute name="optSecondary" type="xsd:string" use="optional"/>
            <xsd:assert test="@optPrimary or not(@optSecondary)" xerces:message="Secondary needs primary..."/>
        </xsd:complexType>          
    </xsd:element>
</xsd:schema>