xmlschema: conditional presence of an attribute  
Author Message
bitbonk





PostPosted: XML and the .NET Framework, xmlschema: conditional presence of an attribute Top

In a XSD is there a way to define a rule that makes an attribute required based on a condition (another attribute has a specific value) Something like: "In case the attribute 'Target' has the value 'File' the Attribute 'Filename' has to be present in the current Element else the Atrribute 'Filename' is optional."


.NET Development17  
 
 
Martin Honnen





PostPosted: XML and the .NET Framework, xmlschema: conditional presence of an attribute Top

Such constraints can be specified using Schematron and can be checked with the help of XSLT stylesheets and an XSLT processor. That way both MSXML and the .NET framework can be used to check assertions/constraints specified with Schematron.

 
 
bitbonk





PostPosted: XML and the .NET Framework, xmlschema: conditional presence of an attribute Top

So am I assuming correctly that xmlschema alone can't do it out of the box

 
 
Martin Honnen





PostPosted: XML and the .NET Framework, xmlschema: conditional presence of an attribute Top

Well the W3C XSD schema language has no instructions to generally specify the presence of one attribute based on the value of another attribute. The language however allows you to define types and to extend or restrict such types. For your particular example you could first define a type alike

<xs:simpleType name="TargetType">
<xs:restriction base="xs:string">
<xs:enumeration value="File"/>
<xs:enumeration value="Stream"/>
</xs:restriction>
</xs:simpleType>


<xs:complexType name="LinkType">
<xs:attribute name="Target" type="TargetType" use="required"/>
<xs:attribute name="Filename" type="xs:string" use="optional"/>
</xs:complexType>

which makes the Filename attribute optional, then you could restrict that type alike

<xs:complexType name="FileLinkType">
<xs:complexContent>
<xs:restriction base="LinkType">
<xs:attribute name="Target" type="TargetType" use="required" fixed="File"/>
<xs:attribute name="Filename" type="xs:string" use="required"/>
</xs:restriction>
</xs:complexContent>
</xs:complexType>

where the Target attribute value is fixed as "File" and then the Filename attribute is required. However in any instance XML document you would then need e.g.

<Link xsi:type="FileLinkType" Target="File" Filename="file.xml"/>

to require the restricted type and enforce the constraints during validation.