2017-01-03 138 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>