【问题标题】:How do I require that an element has either one set of attributes or another in an XSD schema?如何要求元素在 XSD 架构中具有一组属性或另一组属性?
【发布时间】:2011-02-17 21:51:36
【问题描述】:

我正在处理一个标记必须具有一组属性或另一组属性的 XML 文档。例如,它需要看起来像 <tag foo="hello" bar="kitty" /><tag spam="goodbye" eggs="world" />,例如

<root>
    <tag foo="hello" bar="kitty" />
    <tag spam="goodbye" eggs="world" />
</root>

所以我有一个 XSD 架构,我使用 xs:choice 元素在两个不同的属性组之间进行选择:

<xsi:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema" attributeFormDefault="unqualified" elementFormDefault="qualified">
    <xs:element name="root">
        <xs:complexType>
            <xs:sequence>
                <xs:element maxOccurs="unbounded" name="tag">
                    <xs:choice>
                        <xs:complexType>
                            <xs:attribute name="foo" type="xs:string" use="required" />
                            <xs:attribute name="bar" type="xs:string" use="required" />
                        </xs:complexType>
                        <xs:complexType>
                            <xs:attribute name="spam" type="xs:string" use="required" />
                            <xs:attribute name="eggs" type="xs:string" use="required" />
                        </xs:complexType>
                    </xs:choice>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xsi:schema>

但是,当使用 lxml 尝试加载此架构时,我收到以下错误:

>>> from lxml import etree  
>>> etree.XMLSchema( etree.parse("schema_choice.xsd") )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "xmlschema.pxi", line 85, in lxml.etree.XMLSchema.__init__ (src/lxml/lxml.etree.c:118685)
lxml.etree.XMLSchemaParseError: Element '{http://www.w3.org/2001/XMLSchema}element': The content is not valid. Expected is (annotation?, ((simpleType | complexType)?, (unique | key | keyref)*))., line 7

由于错误在于我的 xs:choice 元素的放置,我尝试将它放在不同的位置,但无论我尝试什么,我似乎都无法使用它来定义一个标签来拥有其中一个一组属性(foobar)或另一个(spameggs)。

这甚至可能吗?如果是这样,那么正确的语法是什么?

【问题讨论】:

    标签: python xml validation schema lxml


    【解决方案1】:

    很遗憾,不能在 XML 模式中对属性使用选择。您将需要在更高级别实施此验证。

    【讨论】:

    • 确实如此。我强烈建议将 RELAX NG 用于任何类型的 XML 验证,除非您需要它来执行其他需要 XML Schema(XSLT、XQuery、WS-* 等)的东西。事实上,lxml 可以在 Python 中处理 RELAX NG - 见stackoverflow.com/questions/1254919/…
    • 你能把我链接到某处证实这一点的文档吗?
    • @Pavel:感谢您的提示,我以后在编写自己的模式时一定会考​​虑到这一点;不幸的是,目前我只是在调试另一家公司的某人编写的无效架构,所以我被 XSD 困住了。
    • @Eli:官方规范并没有明确说明,它隐含在各种构造的定义中。也就是说,一个简单的 google 搜索:google.com/search?q=xml+schema+attribute+choice - 将为您提供很多参考,以解决在许多地方提出的这个问题,包括官方 XML 邮件列表,到处都有相同的答案。
    • 我认为您不会发现规范中缺少功能。我能做的最好的事情是链接到 Michael Kay 的电子邮件,他是一位广受赞誉的 XML 技术专家:stylusstudio.com/xmldev/200503/post90100.html
    猜你喜欢
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    • 2012-09-09
    • 1970-01-01
    • 2023-03-23
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多