【问题标题】:XSD - Validate attribute value based on attribute value in parent elementXSD - 根据父元素中的属性值验证属性值
【发布时间】:2014-11-10 19:29:22
【问题描述】:

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

示例:

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

伪解:

&lt;rule condition="@otherAttr == true &amp;&amp; //child1/@myAttr != false" /&gt; 之类的内容添加到“child3”复杂类型的定义中...

示例:

<?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>

【问题讨论】:

标签: xml xsd xsd-validation


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多