Different sub-elements depending on attribute/element value

*爱你&永不变心* 提交于 2019-12-06 00:10:51

The best solution is to remove the <type/> element and only have a xs:choice for <a/> and <b/> and let the application consuming the xml sort out the type.

Another solution might be to have a xs:choice for <a/> and <b/> use an xslt script to do a validation of the <type/> element in relation to <a/> and <b/>.

First validate the xml against the xmlschema then use the xslt to do a transformation on it, if the result of the transform is empty string it is valid otherwise show the resulting string as an error message.

Something like this...

XmlSchema:

  <xs:element name="some-element">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="type" type="xs:integer" />
        <xs:choice>
          <xs:element name="a" type="xs:string" />
          <xs:element name="b" type="xs:string" />
        </xs:choice>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Xslt:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:demo="uri:demo:namespace">
  <xsl:output method="text" />
  <xsl:template match="/demo:some-element">
    <xsl:if test="type = 1 and not(demo:a)">
      When type equals 1 element a is requred.
    </xsl:if>
    <xsl:if test="type = 2 and not(demo:b)">
      When type equals 2 element b is requred.
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>

No, XML Schema 1.0 cannot do this.

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