XML Restrict based on another element value

杀马特。学长 韩版系。学妹 提交于 2019-12-10 22:53:13

问题


Basically I have my XML version 1.0 and I have a complex element with following example:

<tile>
  <position>5</position>
  <type>floor</type>
  <towerPlacement>true</towerPlacement>
</tile>

I have defined following in my XML Schema:

<xs:element name="type">
   <xs:simpleType>
   <xs:restriction base="xs:string">
   <xs:enumeration value="road"/>
   <xs:enumeration value="floor"/>
   <xs:enumeration value="startPos"/>
   <xs:enumeration value="endPos"/>
   </xs:restriction>
   </xs:simpleType>
</xs:element>

Is there a way to make my towerPlacement true only if type = floor?

<xs:element type="xs:boolean" name="towerPlacement" minOccurs="0" maxOccurs="1" />

回答1:


XSD 1.0

Your constraint cannot be expressed in XSD 1.0.

XSD 1.1

Your constraint can be expressed in XSD 1.1 using an assertion to state that towerPlacement must only be true if type = 'floor':

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" 
           xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" 
           vc:minVersion="1.1">
  <xs:element name="tile">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="position" type="xs:integer"/>
        <xs:element name="type">
          <xs:simpleType>
            <xs:restriction base="xs:string">
              <xs:enumeration value="road"/>
              <xs:enumeration value="floor"/>
              <xs:enumeration value="startPos"/>
              <xs:enumeration value="endPos"/>
            </xs:restriction>
          </xs:simpleType>
        </xs:element>
        <xs:element name="towerPlacement" type="xs:string"/>
      </xs:sequence>
      <xs:assert test="(type='floor' and towerPlacement='true') 
                       or towerPlacement!='true'"/>
    </xs:complexType>
  </xs:element>
</xs:schema>


来源:https://stackoverflow.com/questions/47694183/xml-restrict-based-on-another-element-value

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