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"/>
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>
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 ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With