XSD - 根据父元素中的属性值验证属性值

时间:2014-11-10 00:14:40

标签: xml xsd xsd-validation

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

示例:

<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" />之类的内容添加到&#39; child3&#39;的定义中。复杂的类型...

示例:

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

1 个答案:

答案 0 :(得分:2)

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

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