【问题标题】:XML Schema reference id of complex type复杂类型的 XML 模式参考 ID
【发布时间】:2016-03-04 17:59:32
【问题描述】:

假设我定义一个 XML 模式如下。考虑一个简单的用户元素,它有一个 id、姓名、电子邮件、年龄和一组他/她是朋友的其他用户。朋友元素将简单地保存他/她是朋友的用户的 ID。 XML 会是这样的:

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

我正在努力创建相应的架构。我目前有下面的架构,但是因为friend 的架构是这样定义的,所以我需要包含嵌套在&lt;friend&gt; 标记内的所有用户元素......这显然是个坏主意。如何更改我的 XML 架构以允许外键引用另一个用户 ID?

当前架构:

<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>

【问题讨论】:

  • 为什么将userType设置为“朋友”的类型?如果您只希望它包含 id,它不应该只是 int 吗?

标签: xml


【解决方案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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 1970-01-01
    • 2013-01-25
    • 2014-03-17
    • 1970-01-01
    相关资源
    最近更新 更多