【问题标题】:Restrict order of XML elements based on attribute基于属性限制 XML 元素的顺序
【发布时间】:2011-04-04 18:14:35
【问题描述】:

我有以下 XML:

<?xml version="1.0"?>

<coll xmlns="http://www.example.org/coll" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.example.org/coll coll.xsd">

    <collection>
        <item action="remove">1</item>
        <item action="add">2</item>
        <item action="add">3</item>
    </collection>

    <collection>
        <item action="add">2</item>
        <item action="remove">1</item>
        <item action="add">3</item>
    </collection>

</coll>   

还有一个 XSD:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/coll"
    xmlns:tns="http://www.example.org/coll" elementFormDefault="qualified">

    <element name="coll" type="tns:coll">
    </element>

    <complexType name="coll">
        <sequence>
            <element name="collection" type="tns:collection" minOccurs="0" maxOccurs="unbounded"></element>
        </sequence>
    </complexType>

    <complexType name="collection">
        <sequence>
            <element name="item" type="tns:item" minOccurs="0" maxOccurs="unbounded"></element>
        </sequence>
    </complexType>

    <complexType name="item">
        <simpleContent>
            <extension base="string">
                <attribute name="action">
                    <simpleType>
                        <restriction base="string">
                            <enumeration value="add"></enumeration>
                            <enumeration value="remove"></enumeration>
                        </restriction>
                    </simpleType>
                </attribute>
            </extension>
        </simpleContent>
    </complexType>

</schema>

我想限制项目元素的顺序,以便删除总是在添加之前。 IE。第一个集合有效,但第二个无效。

我尝试了两个项目元素,一个是 add_item 类型,一个是 remove_item。但这无法验证 XSD,错误是我不能有两个具有不同类型的同名元素。

有什么想法吗?还是有可能?

【问题讨论】:

  • 不在 XML 架构中。你可以使用 schematron。

标签: xml xsd


【解决方案1】:

唯一可行的方法(使用 XSD)是重构您的架构以将操作用作元素名称而不是属性:

<collection>
    <remove>1</remove>
    <add>2</add>
    <add>3</add>
</collection>

这样,您可以在架构中使用序列来确定顺序。

更一般的说明:您的架构设计看起来有点混乱。您的元素名称似乎描述了一种状态(集合、项目),但您在项目上的属性似乎携带了有关您的代码(可能)要采取的操作的实际信息。如果您可以选择设计,您可能需要考虑稍微重新设计。

【讨论】:

  • 好的,谢谢!不幸的是,我无法控制架构设计本身,只能控制 XSD。它表示与外部系统的接口。
猜你喜欢
  • 1970-01-01
  • 2023-03-06
  • 2013-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-01
  • 2019-08-26
  • 2011-05-06
相关资源
最近更新 更多