在XML模式中使用ref

时间:2014-02-17 15:22:40

标签: xml xsd

我正在尝试通过列id属性创建一个包含行引用列的模式。以下xml和xsd将无法验证,因为无法找到该列

如何为以下XML创建架构,以便我可以从行元素引用列id:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<mapping xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <rows>
        <row>
            <column id="123" />
            <column id="124" />
        </row>
        <row>
            <column id="123" />
            <column id="124" />
        </row>
    </rows>

    <columns>
        <column id="123">
            <name>Apple</name>
        </column>

        <column id="124">
            <name>Banana</name>
        </column>
    </columns>

</mapping>

我的xsd看起来像这样,但它不起作用......它无法找到列引用:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<xsd:element name="mapping">
    <xsd:complexType>
        <xsd:sequence>
            <xsd:element name="rows" type="Rows" minOccurs="0" maxOccurs="1"/>
            <xsd:element name="columns"  type="Columns" minOccurs="0" maxOccurs="1"/>
        </xsd:sequence>
    </xsd:complexType>      
    <xsd:key name="PKeyColumn">
        <xsd:selector xpath="columns/column"/>
        <xsd:field xpath="@id"/>
    </xsd:key>      
    <xsd:keyref name="FKeyColumn" refer="PKeyColumn">
        <xsd:selector xpath="rows/row/column"/>
        <xsd:field xpath="@id"/>
    </xsd:keyref>
</xsd:element>

<xsd:complexType name="Row">
    <xsd:sequence>
        <xsd:element ref="column">
            <xsd:complexType>
                <xsd:attribute name="id" use="required" type="xsd:integer" />
            </xsd:complexType>
        </xsd:element>
    </xsd:sequence>
</xsd:complexType>

<xsd:complexType name="Rows">
    <xsd:sequence>
        <xsd:element name="row" type="Row" minOccurs="1" maxOccurs="unbounded">
            <xsd:unique name="UKeyColumn">
                <xsd:selector xpath="column"/>
                <xsd:field xpath="@id"/>
            </xsd:unique>   
        </xsd:element>
    </xsd:sequence>
</xsd:complexType>  

<xsd:complexType name="Columns">
    <xsd:sequence>
        <xsd:element name="column" type="Column" minOccurs="1" maxOccurs="unbounded"/>
     </xsd:sequence>
</xsd:complexType>

<xsd:complexType name="Column">
    <xsd:sequence>
        <xsd:element name="name" type="xsd:string" minOccurs="1" maxOccurs="1"/>
    </xsd:sequence>
    <xsd:attribute name="id" type="xsd:integer" />
</xsd:complexType>

</xsd:schema>

1 个答案:

答案 0 :(得分:0)

您的架构存在一些小问题 - element ref="column"类型中的Row需要name而不是ref,而且需要maxOccurs大于1(默认值)。

<xsd:complexType name="Row">
    <xsd:sequence>
        <xsd:element name="column" maxOccurs="unbounded">

一旦我修复了这些错误,这一切都会很好地验证,并且交叉引用要求(row中提到的每个列ID必须与columns部分中的列ID对应)才能满足keykeyref