Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making an attribute required only if another attribute is set

Tags:

xsd

Is it possible to make an attribute required iff another attribute is set?

E.g. In the following code, viewId attribute has to be made required, iff action attribute is set.

XML:

<node id="id1" destination="http://www.yahoo.com" />
<node id="id2" action="demo" viewId="demo.asp"/>

If this is possible, could you please show me how this is done. As of now, I have viewId set required in all the cases, because of which the 1st node element fails validation.

<xsd:attribute name="focusViewId" type="xsd:anyURI" use="required"/>
like image 327
Arjun Avatar asked Oct 05 '12 12:10

Arjun


2 Answers

It is not possible with XSD 1.0 alone. You have to employ the use of another XML schema language, in addition to or instead of XSD, or move to XSD 1.1.

Another alternative may be to restructure your schema. If @destination is mutually exclusive with { @action, @viewId} maybe you could use elements instead which would then allow you to employ xsd:choice.

UPDATE: for an XSD 1.1

<?xml version="1.0" encoding="utf-8" ?>
<!-- XML Schema generated by QTAssistant/XSD Module (http://www.paschidev.com) -->
<xsd:schema elementFormDefault="qualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:element name="node">
        <xsd:complexType>
            <xsd:attribute name="id" type="xsd:ID" use="required"/>
            <xsd:attribute name="destination" type="xsd:string"/>
            <xsd:attribute name="action" type="xsd:string"/>
            <xsd:attribute name="viewId" type="xsd:string"/>
            <xsd:assert test="(@viewId) or not(@action)" />
        </xsd:complexType>
    </xsd:element>
</xsd:schema>
like image 164
Petru Gardea Avatar answered Oct 05 '22 13:10

Petru Gardea


You can create an abstract complex type for your element "node" (let's call it abstactNode) which contains the definition of @id.

Then create a complex type "nodeWithDestination" that extends abstactNode, with the definition of the @destination.

An a second complex type "nodeWithActionAndViewId" that extends abstactNode as well, with @action and @viewId attribute definitions.

Your XML would look like this:

<node id="id1" destination="http://www.yahoo.com" xsi:type="nodeWithDestination"/>
<node id="id2" action="demo" viewId="demo.asp" xsi:type="nodeWithActionAndViewId"/>

Would that match your need ?

like image 42
Eniac Avatar answered Oct 05 '22 12:10

Eniac