XSD: How to validate the XML file according to value of some tag?
I was trying to validate this XML file .开发者_如何转开发.. where if
<tag1>
is "Y" then<tag2>
must appearif
<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 ..
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.
It's a known fact that this is a handycap of XML schema. But I would appreciate your approach of trying the <choice>
tag. It could be successful if your conditions were something like this:
- If
<tag1>
is required and appears first then<tag2>
isn't required (and appears as second tag) - 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 name="tag2" type="xs:string" minOccurs="0" />
</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>
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).
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 ..
精彩评论