问题
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