Example of extending complex types in XSD?

对着背影说爱祢 提交于 2019-12-06 16:03:54

You can use xs:extension to extend NewContractType from ExistingContractType:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="ExistingContract" type="ExistingContractType"/>

  <xs:complexType name="ExistingContractType">
    <xs:sequence>
      <xs:element name="first" type="FirstType"/>
      <xs:element name="second" type="SecondType"/>
    </xs:sequence> 
  </xs:complexType>

  <xs:complexType name="NewContractType">
    <xs:complexContent>
      <xs:extension base="ExistingContractType">
        <xs:sequence>
          <xs:element name="additionalData" type="AdditionalDataType"/>
        </xs:sequence>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:element name="NewContract" type="NewContractType"/>

  <xs:complexType name="FirstType"/>
  <xs:complexType name="SecondType"/>
  <xs:complexType name="AdditionalDataType"/>

</xs:schema>

In addition to the technique described by @kjhughes, you can use a named ModelGroup:

<xs:group name="common">
    <xs:sequence>
      <xs:element name="first" type="FirstType"/>
      <xs:element name="second" type="SecondType"/>
    </xs:sequence>
</xs:group> 

<xs:complexType name="ExistingContractType">
   <xs:sequence>
    <xs:group ref="common"> 
   </xs:sequence>
</xs:complexType>

<xs:complexType name="NewContractType">
   <xs:sequence>
    <xs:group ref="common">
    <xs:element name="additionalData" type="AdditionalDataType"/> 
   </xs:sequence>
</xs:complexType>

Both these are very similar from the point of view of maintainability. There is a difference in terms of instance validation: a type derived by extension can be used in place of the base type if you specify xsi:type on the instance element, unless you block it. They might also have different results if you are using data binding tools (I don't know), and you might feel that they have different "semantics" in terms of modelling the real-world relationship between the objects being represented.

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