XSD - 根据父元素中的属性值验证属性值 [英] XSD - Validate attribute value based on attribute value in parent element

查看:35
本文介绍了XSD - 根据父元素中的属性值验证属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以定义一个 XSD 结构,使得元素上的 和 属性只有在父(直接/间接)元素上的属性具有特定值时才能具有特定值?

Is it possible to define an XSD structure such that and attribute on an element can have a certain value only if an attribute on a parent (direct/indirect) element has a certain value?

示例:

<root>
    <child1 myAttr="true">
        <child2>
            <child3 otherAttr="false" /> <!-- 'otherAttr' can only be 'false' if 'myAttr' is 'true' -->
        </child2>
    </child1>
</root>

伪解决方案:

添加类似 <rule condition="@otherAttr == true &&//child1/@myAttr != false"/> 到 'child3' 的定义复杂类型...

To add something like <rule condition="@otherAttr == true && //child1/@myAttr != false" /> to the definition of the 'child3' complex type...

示例:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema elementFormDefault="qualified" 
       xmlns:xs="http://www.w3.org/2001/XMLSchema" 
       xmlns="http://My.Schema.Namespace" 
       targetNamespace="http://My.Schema.Namespace">

<xs:element name="root">
  <xs:sequence>
      <xs:element name="child1" type="child1Type" />
  </xs:sequence>
</xs:element>

<xs:complexType name="child1Type">
  <xs:sequence>
    <xs:element name="child2" type="child2Type" />
  </xs:sequence>
  <xs:attribute name="myAttr" type="xs:boolean" use="optional" default="false" />
</xs:complexType>

<xs:complexType name="child2Type">
  <xs:sequence>
    <xs:element name="child3" type="child3Type" />
  </xs:sequence>
</xs:complexType>

<xs:complexType name="child3Type">
  <xs:attribute name="otherAttr" type="xs:boolean" use="optional" default="true" /> 
  <rule condition="@otherAttr == true && //child1/@myAttr != false" />
</xs:complexType>

推荐答案

要定义任何类型的交叉验证,您需要 XSD 1.1,它允许任意断言.断言可以访问放置断言的元素的子树,而不是其祖先,因此您的情况下的断言需要在 child1 元素上进行.你还没有很清楚地解释实际情况是什么,但它会像

To define any kind of cross-validation you need XSD 1.1, which allows arbitrary assertions. An assertion has access to the subtree of the element where the assertion is placed, and not to its ancestors, so the assertion in your case needs to go on the child1 element. You haven't explained very clearly what the condition actually is, but it would be something like

<xs:assert test="if (@myAttr = 'true') then child2/child3/@otherAttr = 'false' else true()"/>

这篇关于XSD - 根据父元素中的属性值验证属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆