Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

XML Validation on attributes

Status
Not open for further replies.

sroberts82

Programmer
Oct 11, 2005
36
US
Hi,
Im currently looking at using XML Schemas to validate my code. Here is my problem. I want to validate by attribute so that if attribute is x i have 1 child element otherwise i have 2:

<element att="x">
<cap>a</cap>
<cap>b</cap>
</element>

<element att="y">
<cap>a</cap>
<cap>b</cap>
</element>

The only way i can see to it is to define 2 different elements x and y but that doesnt make sense it the context I am using as X and Y ARE attributes of my element and it makes the XML more complex which is not good for the user who has to write it. So my question is can I validate based on attribute? Thanks in advance,
 
[1] That is the kind of constraint not readily making itself available to scope of validation of the w3c xml schema language. It is of the kind of constraint commonly called co-occurence.

[2] If you run the xml document against a simple self-made template xsl document, but to the point of the bigger idea, in tandem with the validation by WXSL, you can get satisfaction quite easily. The template can be constructed very simply like this.
[tt]
<?xml version="1.0" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="<xsl:eek:utput method="text" />
<xsl:template match="element"> <!-- the context -->
<xsl:choose>
<xsl:when test="not ((@att = 'x' and count(child::*) = 1) or (@att = 'y' and count(child::*) = 2))">
<xsl:text>Assertion fails:&#x0a;"If the &lt;element&gt;'s attribute @att is x, it should only contain one child node, or &#x0a;if the &lt;element&gt;'s attribute @att is y, it should only contain two child nodes."&#x0a;</xsl:text>
</xsl:when>
<xsl:eek:therwise>
<xsl:text>Assertion succeeds.&#x0a;</xsl:text>
</xsl:eek:therwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
[/tt]
From the output of the transformation, you get the validation result.

[3] From the simple demo in [2], and if you want more sophisticated industry-wide device, you can take a look at Schematron. The construction of a validation basically is not very different from the [2] but loaded with systematic and enough sophiscation on the messaging.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top