Different subelements depending on attribute / element value

Another XSD question is how can I achieve that both XML elements are valid:

<some-element>
  <type>1</type>
  <a>...</a>
</some-element>

<some-element>
  <type>2</type>
  <b>...</b>
</some-element>

Subelements (either <a>, or <b>) must be content dependent <type>(may also be an attribute). It would be so simple in RelaxNG, but RelaxNG does not support key integrity :(

Is there any way to implement this in XSD?

Note: XML Schema version 1.1 supports <xs:alternative>what might be a solution, but afaik does not yet support any reference implementation (for example, libxml2). Therefore, I am looking for workarounds. The only way I came up with:

<type>1</type>
<some-element type="1">
    <!-- simple <xs:choice> between <a> and <b> goes here -->
    <a>...</a>
</some-element>
<!-- and now create a keyref between <type> and @type -->
+3
source share
2 answers

<type/> xs:choice <a/> <b/>, , xml, .

xs:choice <a/> <b/> xslt script <type/> <a/> <b/>.

xml xmlschema, xslt, , , .

- ...

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>
+3

, XML Schema 1.0 .

+2

Source: https://habr.com/ru/post/1744998/


All Articles