我试图使两个xml属性相互排斥。如何创建xsd模式来捕获此类场景?
我想要一个

<elem value="1" />
<elem ref="something else" />

但不是
<elem value="1" ref="something else" />

最佳答案

因为在alnitak的回答中提到了RelaxNG,这里有一个解决方案
使用relaxng(在大多数情况下,比w3c更好的语言
模式)。注意elem定义中的or():

start = document
document = element document {elem+}
elem = element elem {ref | value}
ref = attribute ref {text}
value = attribute value {xsd:integer}

如果我有这个XML文件:
<document>
    <elem value="1" />
    <elem ref="something else" />
</document>

它被rnvxmlint接受:
 % rnv attributes-exclusive.rnc attributes-exclusive.xml
 attributes-exclusive.xml

 % xmllint --noout --relaxng attributes-exclusive.rng attributes-exclusive.xml
 attributes-exclusive.xml validates

如果添加XML文件:
<elem value="1" ref="something else" />

我得到了我想要的验证错误(请注意,错误消息
是次优的):
% rnv attributes-exclusive.rnc attributes-exclusive.xml
attributes-exclusive.xml
attributes-exclusive.xml:4:0: error: attribute ^ref not allowed
required:
       after

% xmllint --noout --relaxng attributes-exclusive.rng attributes-exclusive.xml
attributes-exclusive.xml:4: element elem: Relax-NG validity error : Invalid attribute value for element elem
attributes-exclusive.xml fails to validate

09-10 06:02
查看更多