【问题标题】:Expressing a "must exist" relationship in XML schema在 XML 模式中表达“必须存在”的关系
【发布时间】:2017-04-05 21:32:38
【问题描述】:

我有一个如下所示的 XML 文档(最小可重现示例):

<root start="baz">
    <child name="foo">...</child>
    <child name="bar">...</child>
    <child name="baz">...</child>
</root>

我希望我的架构强制执行这样一个事实,即根元素上的 start 属性必须引用具有该名称的现有 child 节点。如果没有具有该值的 name 属性的子节点,则验证应该失败。换句话说,上面应该验证,但这应该

<root start="baz">
    <child name="foo">...</child>
    <child name="bar">...</child>
</root>

有什么好的方法可以做到这一点?我真的需要使用带有合适 XPath 表达式的assert,还是有更自然的方式在 XSD 中表达它?谢谢。

PS:假设start 是必需属性,而name 子属性在适当的范围内被标记为唯一。

【问题讨论】:

    标签: xml xpath xsd schema


    【解决方案1】:

    您正在寻找xsd:key/xsd:keyref。见:

    XML Schema key/keyref - how to use them?

    大概是这样的:

    <xsd:key name="root-child-name"> 
      <xsd:selector xpath="root/child"/> 
      <xsd:field xpath="@name"/> 
    </xsd:key> 
    <xsd:keyref name="root-start" refer="root-child-name"> 
      <xsd:selector xpath="root"/> 
      <xsd:field xpath="@start"/> 
    </xsd:keyref> 
    

    【讨论】:

    • 我必须将 xpath="." 放在 keyref 中才能为我工作,否则我该怎么做?如果 root 实际上是根元素,我不能将 keyref 放在文档树中更高的位置,因此 xpath 无法工作,并且选择器中显然不支持斜杠。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    • 2014-02-13
    • 2023-02-13
    • 2017-02-10
    • 1970-01-01
    • 2019-12-24
    相关资源
    最近更新 更多