2017-01-03 119 views
0

我想要一個抽象類(例如「車輛」)並且想從其派生其他類(例如「汽車」和「摩托車」)。派生自抽象類,僅引用派生類

現在我想引用我的主要元素中的抽象類,以便在xml文件中只允許使用來自「車輛」的每個派生類。我只是不確定如何做到這一點,任何幫助,將不勝感激。

示例XML:

<main xmlns="http://www.exampleURI.com/example"> 
    <car> 

    </car> 
    <motorbike> 

    </motorbike> 
</main> 

例XSD:

<?xml version="1.0"?> 
<xs:schema targetNamespace="http://www.exampleURI.com/example" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:ex="http://www.exampleURI.com/example"> 
    <xs:element name="main" type="ex:main"/> 
    <xs:complexType name="main"> 
     <xs:sequence> 
      <xs:element name="vehicles" type="ex:vehicles"/> 
     </xs:sequence> 
    </xs:complexType> 
    <xs:element name="vehicles" type="ex:vehicles"/> 
    <xs:complexType name="vehicles" abstract="true"> 
     <xs:sequence/> 
    </xs:complexType> 
    <xs:element name="car" type="ex:car"/> 
    <xs:complexType name="car"> 
     <xs:complexContent> 
      <xs:extension base="ex:vehicles"> 
       <xs:sequence/> 
      </xs:extension> 
     </xs:complexContent> 
    </xs:complexType> 
    <xs:element name="motorbike" type="ex:motorbike"/> 
    <xs:complexType name="motorbike"> 
     <xs:complexContent> 
      <xs:extension base="ex:vehicles"> 
       <xs:sequence/> 
      </xs:extension> 
     </xs:complexContent> 
    </xs:complexType> 
</xs:schema> 
+0

請出示你迄今爲止寫的XML Schema文檔。謝謝。 –

+0

事情是iam在Enterprise Architect中直觀地做到這一點,但我可以從中顯示生成的代碼。一秒。 – Cyriac

回答

1

好像取代基會做的伎倆。另外,在main中,您需要使用ref屬性來確保引用正確的元素,並允許無限數量的子元素。

<?xml version="1.0"?> 
<xs:schema targetNamespace="http://www.exampleURI.com/example" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:ex="http://www.exampleURI.com/example"> 
    <xs:element name="main" type="ex:main"/> 
    <xs:complexType name="main"> 
     <xs:sequence> 
      <xs:element ref="ex:vehicles" maxOccurs="unbounded"/> 
     </xs:sequence> 
    </xs:complexType> 
    <xs:element name="vehicles" type="ex:vehicles"/> 
    <xs:complexType name="vehicles" abstract="true"> 
     <xs:sequence/> 
    </xs:complexType> 
    <xs:element name="car" type="ex:car" substitutionGroup="ex:vehicles"/> 
    <xs:complexType name="car"> 
     <xs:complexContent> 
      <xs:extension base="ex:vehicles"> 
       <xs:sequence/> 
      </xs:extension> 
     </xs:complexContent> 
    </xs:complexType> 
    <xs:element name="motorbike" type="ex:motorbike" substitutionGroup="ex:vehicles"/> 
    <xs:complexType name="motorbike"> 
     <xs:complexContent> 
      <xs:extension base="ex:vehicles"> 
       <xs:sequence/> 
      </xs:extension> 
     </xs:complexContent> 
    </xs:complexType> 
</xs:schema> 

這份文件是針對上述模式是有效的:

<main xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.exampleURI.com/example test.xsd" 
xmlns="http://www.exampleURI.com/example"> 
    <car></car> 
    <motorbike></motorbike> 
</main>