Xsd XML模式:当存在另一个元素时,要求该元素存在
我的模式允许一个特定的元素是可选的,但是当我稍后在文件中遇到一个不同的也是可选的元素时,我需要前一个元素存在。如何通过XSD确保这一点 例如:Xsd XML模式:当存在另一个元素时,要求该元素存在,xsd,Xsd,我的模式允许一个特定的元素是可选的,但是当我稍后在文件中遇到一个不同的也是可选的元素时,我需要前一个元素存在。如何通过XSD确保这一点 例如: <settings> <file name="narf.txt"/> <metafile name="narf.meta"/> <filtermeta>true</filtermeta> </settings> 真的 应该是有效的, <settings>
<settings>
<file name="narf.txt"/>
<metafile name="narf.meta"/>
<filtermeta>true</filtermeta>
</settings>
真的
应该是有效的,
<settings>
<file name="narf.txt"/>
<metafile name="narf.meta"/>
</settings>
及
也应该是有效的,
<settings>
<file name="narf.txt"/>
<filtermeta>true</filtermeta>
</settings>
真的
应无效。请尝试以下架构定义:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="settings">
<xs:complexType>
<xs:sequence>
<xs:element name="file">
<xs:complexType>
<xs:attribute name="name" type="xs:string"/>
</xs:complexType>
</xs:element>
<xs:sequence minOccurs="0">
<xs:element name="metafile">
<xs:complexType>
<xs:attribute name="name" type="xs:string"/>
</xs:complexType>
</xs:element>
<xs:element minOccurs="0" name="filtermeta" type="xs:string"/>
</xs:sequence>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
正如所料。您可以将
filtermeta
作为图元文件元素的可选属性。看起来这在XML Schema 1.0中是不可能的-如果不是这样,未来的规范可能会允许,至少正在讨论中。谢谢。虽然这解决了我为说明我的问题而发布的简单示例,但它并不能解决根本的问题,尤其是当元素在模式逻辑和层次结构中进一步分离时。也许可以让它与代码复制一起工作,但那太难看了。对于更一般的情况,这将很快变得非常不愉快。类似Schematron的东西在这里会更好——您可以放松XSD,以便它关注基本结构和类型约束。然后,“跨域”验证规则(例如,如果元素“A”存在,则元素“B”必须存在)可以写入Schematron规则。例如,您可以为提供的测试用例编写Schematron规则,如下所示:如果filtermeta存在,则元文件也必须存在
谢谢!Schematron对我的问题来说太过分了,但知道它确实很好!
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="settings">
<xs:complexType>
<xs:sequence>
<xs:element name="file">
<xs:complexType>
<xs:attribute name="name" type="xs:string"/>
</xs:complexType>
</xs:element>
<xs:sequence minOccurs="0">
<xs:element name="metafile">
<xs:complexType>
<xs:attribute name="name" type="xs:string"/>
</xs:complexType>
</xs:element>
<xs:element minOccurs="0" name="filtermeta" type="xs:string"/>
</xs:sequence>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
cvc-complex-type.2.4.a: Invalid content was found starting with element 'filtermeta'. One of '{metafile}' is expected.