views:

204

answers:

4

Hi! I was trying to validate this XML file ... where if

  1. <tag1> is "Y" then <tag2> must appear

  2. if <tag1> is "N" then <tag2> must not appear ..

    <parent>
      <a>
        <tag1>Y</tag1>
        <tag2>sometext</tag2>
      </a>
      <a>
        <tag1>N</tag1>
      </a>
    </parent>
    

I tried <choice> tag but doesn't seem to work .. :( I have come to conclusion that this feature is not available in XSD ..

Can you guide me atleast some alternative to implement this ? by the way I am using Visual Studio 2005 ..

+6  A: 

You cannot validate things like that with XSD.

XML schema is not designed and not intended to check "intra-tag" relationships, e.g. "tag2 must be present if tag1's value is 'Y'" - just cannot be done, sorry.

If you need to check these kind of conditions, you'll have to look at Schematron to do that.

marc_s
+1 Schematron looks interesting...
skaffman
I know a little bit about schematron .. sounds interesting .. but not much tools developed for it .. and even visual studio doesn't support it ...
+1  A: 

Unfortunately this problem cannot be fixed using XSD. The reason is that XSD can only be used to define the structure (syntax) of XML-Files. What you would like to do is to couple the syntax to some semantic properties (some TAG must have a certain content to decide on the syntax of some TAGS nearby).

zlajo
+2  A: 

Its a known fact that .. this is a handy-cap with XML-schema ..
But I would appreciate your approach of .. trying <choice> tag ..
we could have been successful if your conditions were something like this .. :
1)if <tag1> is required and appears first then <tag2> isn't required (and appears as second tag )
2)If <tag2> is required and appears first then <tag1> isn't required (and appears as second)
the code is:

  <xs:element name="parent">
    <xs:complexType>
        <xs:sequence>
        <xs:element name="a" maxOccurs="unbounded">
          <xs:complexType>
            <xs:choice>
              <xs:sequence>
              <xs:element name="tag1" type="xs:boolean" />
              <xs:element minOccurs="0" name="tag2" type="xs:string" />
              </xs:sequence>
              <xs:sequence>
                <xs:element name="tag2" type ="xs:string"/>
                <xs:element name="tag1" type ="xs:boolean" minOccurs="0"/>
              </xs:sequence>
            </xs:choice>
          </xs:complexType>
        </xs:element>
        </xs:sequence>
    </xs:complexType>
  </xs:element>
infant programmer
Well tried .. +1 .. :)
infant programmer
oh .. good one ... :) thank you :)
A: 

Its not possible with XSD .. But by the way you can work around something like Infant-programmer if the requirement is bit comfortable as shown in her example ..