XSD:如何根据某个标签的值验证 XML 文件? [英] XSD: How to validate the XML file according to value of some tag?
问题描述
我试图验证这个 XML 文件...如果
I was trying to validate this XML file ... where if
<tag1>
为 "Y" 则<tag2>
必须出现
<tag1>
is "Y" then<tag2>
must appear
如果 <tag1>
为N",则 <tag2>
不得出现..
if <tag1>
is "N" then <tag2>
must not appear ..
<parent>
<a>
<tag1>Y</tag1>
<tag2>sometext</tag2>
</a>
<a>
<tag1>N</tag1>
</a>
</parent>
我尝试了 <choice>
标记,但似乎不起作用.. :( 我得出的结论是 XSD 中没有此功能..
I tried <choice>
tag but doesn't seem to work .. :( I have come to conclusion that this feature is not available in XSD ..
你能指导我至少一些替代方案来实现这个吗?顺便说一句,我使用的是 Visual Studio 2005 ..
Can you guide me atleast some alternative to implement this ? by the way I am using Visual Studio 2005 ..
推荐答案
这是一个众所周知的事实,这是一个 XML 模式的便利.但我会很感激你尝试 <choice>
标记的方法.如果您的条件是这样的,它可能会成功:
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:
- 如果
<tag1>
是必需的并且首先出现,那么<tag2>
不是必需的(并且作为第二个标签出现) - 如果
<tag2>
是必需的并且首先出现,那么<tag1>
不是必需的(并且作为第二个出现)
- 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)
代码是:
<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>
这篇关于XSD:如何根据某个标签的值验证 XML 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!