XML Schema reference id of complex type

时间:2016-03-04 17:59:32

标签: xml

Suppose I define an XML schema as follows. Consider a simple User element that has an id, name, email, age, and a set of other Users he/she is friends with. The friend element would simply hold the id of the User he/she is friends with. The XML would like something like:

<user>
    <id>1</id>
    <name>Alice</name>
    ...
    <friend>2</friend>
    <friend>3</friend>
</user>

I'm struggling to create the corresponding schema. I currently have the schema below, but because the schema for friend is defined as such, I need to include all of the User element nested inside the <friend> tag.... which is clearly a bad idea. How can I change my XML schema to allow for a foreign key reference to another User id?

Current schema:

<xsd:complexType name="userType">
    <xsd:sequence>
        <xsd:element name="id" type="xsd:int"></xsd:element>
        [ ... many more fields ...]
        <xsd:element name="friend" type="userType" minOccurs="0" maxOccurs="unbounded"></xsd:element>
    </xsd:sequence>
</xsd:complexType>

1 个答案:

答案 0 :(得分:1)

如果您愿意将通用名称作为ID(而不是仅限整数),则可以利用XSD中的ID,IDREF,IDREFS definitions。您的架构将如下所示:

<xsd:complexType name="userType">
    <xsd:sequence>
        <xsd:element name="id" type="xsd:ID"/>
        [ ... many more fields ...]
        <xsd:element name="friend" type="xsd:IDREF" minOccurs="0" maxOccurs="unbounded"/>
    </xsd:sequence>
</xsd:complexType>

但是,由于这些类型最初仅定义为属性类型,因此某些XSD处理器可能会遇到问题。针对兼容性和紧凑性进行了优化的版本如下所示:

<xsd:complexType name="userType">
    <xsd:sequence>
        [ ... many fields ...]
        <xsd:element name="friends">
            <xsd:complexType>
                <xsd:attribute name="ids" type="xsd:IDREFS"/>
            </xsd:complexType>
        </xsd:element>
    </xsd:sequence>
    <xsd:attribute name="id" type="xsd:ID"/>
</xsd:complexType>

相应的XML将是

<user id="1">
    <name>Alice</name>
    ...
    <friends ids="2 3"/>
</user>