XML schema attribute dependancies

2019-08-20 01:40发布

I'd like to ask if it's possible in XML xsd schema declare dependant attributes...

Example:

<xsd:simpleType name="packCategories">
 <xsd:restriction base="xsd:byte">
  <xsd:minInclusive value="0"/>
  <xsd:maxInclusive value="4"/>
 </xsd:restriction>
</xsd:simpleType>

<xs:element name="pack">
 <xs:complexType>
   <!-- elements go here -->
   <xs:attribute type="packCategories" name="category" use="required"/>
   <xs:attribute type="xs:string" name="explanation" use="optional"/>
 </xs:complexType>
</xs:element>

Everything seems fine here, HOWEVER, i want the explanation attribute to be MANDATORY if category attribute is equal to 4. Is that possible? Maybe with elements then?

标签: xml xsd schema
1条回答
冷血范
2楼-- · 2019-08-20 02:34

If you're using XML Schema 1.0, you cannot express such a constraint in the schema, but you could use Schematron or check it at the application level.

If you're using XML Schema 1.1, you can specify co-occurrence constraints via XPath 2.0 using xs:assert like this:

  <xs:element name="pack">
    <xs:complexType>
      <!-- elements go here -->
      <xs:attribute type="packCategories" name="category" use="required"/>
      <xs:attribute type="xs:string" name="explanation" use="optional"/>
      <xs:assert test="@explanation or @packCategories != 4"/>
    </xs:complexType>
  </xs:element>
查看更多
登录 后发表回答