首页 > 解决方案 > Xsd。两个实体层次结构的继承声明

问题描述

假设我有两个类层次结构:

class Cell {
    string data;
}

// extends Cell with additional property `label`
class Cell2 : Cell {
    string label;
}

class Row {
    Cell[] cells;
}

// extends Cell with additional property `label`
// `cells` property is an array of `Cell2`
class Row2 : Row {
    string label;
}

Row 包含一个 Cell 实例数组,Row2 包含一个 Cell2 实例数组。这是此实体的 xsd:

<xs:complexType name="cell">
    <xs:attribute name="data"/>
</xs:complexType>
<xs:complexType name="cell2">
    <xs:complexContent>
        <xs:extension base="cell">
            <xs:attribute name="label"/>
        </xs:extension>
    </xs:complexContent>
</xs:complexType>
<xs:complexType name="row">
    <xs:sequence maxOccurs="unbounded">
        <xs:element name="cell" type="cell"/>
    </xs:sequence>
</xs:complexType>
<!-- Here is the problem: row2 should cointains cell2 -->
<xs:complexType name="row2">
    <xs:complexContent>
        <xs:extension base="row">
            <xs:attribute name="label"/>
        </xs:extension>
    </xs:complexContent>
</xs:complexType>

然而,这个 xsd 忽略了 Row2 应该包含 Cell2 实例的数组,而不是 Cell 实例。如何使用 xsd 声明这种关系?

标签: inheritancexsd

解决方案


您需要明确声明 Row2 包含 Cell2,如下所示:

<xs:complexType name="cell">
    <xs:attribute name="data"/>
</xs:complexType>
<xs:complexType name="cell2">
    <xs:complexContent>
        <xs:extension base="cell">
            <xs:attribute name="label"/>
        </xs:extension>
    </xs:complexContent>
</xs:complexType>
<xs:complexType name="row">
    <xs:sequence maxOccurs="unbounded">
        <xs:element name="cell" type="cell"/>
    </xs:sequence>
</xs:complexType>
<xs:complexType name="row2">
    <xs:complexContent>
        <xs:sequence maxOccurs="unbounded">
            <xs:element name="cell" type="cell2"/>
        </xs:sequence>
        <xs:attribute name="label"/>
    </xs:complexContent>
</xs:complexType>

我怀疑您已经知道这一点,并且您可能想要创建比这个示例更复杂的东西。如果我是对的,那么我建议您阅读 XSD 规范或其他在线教程中的复杂类型继承。有多种方法可以在 XSD 模型中对面向对象的结构进行建模。


推荐阅读