XSD - Validate attribute value based on attribute value in parent element

霸气de小男生 提交于 2021-02-08 10:44:27

问题


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?

Example:

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

Pseudo Solution:

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

Example:

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


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()"/>


来源:https://stackoverflow.com/questions/26834921/xsd-validate-attribute-value-based-on-attribute-value-in-parent-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!