XML and XSD - use element name as replacement of xsi:type for polymorphism

前端 未结 1 1875
余生分开走
余生分开走 2021-01-05 23:13

Taking the W3C vehicle XSD as an example:



        
相关标签:
1条回答
  • 2021-01-05 23:54

    There is a common design pattern around this, you can use sub-types (as you are already doing), and elements in a substitution group. Elements in the substitution group have to be of a sub-type of the element they are substituted for.

    Unfortuntaly, substitution group elements need to be defined as global elements. So you would have this:

    <complexType name="MeansOfTravel">
      <complexContent>
        <sequence>        
          <element ref="transport"/>
        </sequence>
      </complexContent>
    </complexType>
    
    <element name="transport" type="target:Vehicle"/>
    <element name="plane" type="target:Plane" substitutionGroup="target:transport"/>
    

    Then, in your XML document you can use:

    <meansOfTravel>
        <plane>...</plane>
    </meansOfTravel>
    

    More info on substitution groups here. And no, unfortunately the parser cannot guess this, so you still have to list the elements :( There is one advantage over a choice though: the schema can be extended externally, by importing it, without modifying it. The choice could not be extended.

    0 讨论(0)
提交回复
热议问题