【问题标题】:xml validation: validating a URI typexml 验证:验证 URI 类型
【发布时间】:2011-03-23 19:54:54
【问题描述】:

我正在使用 python 的 lxml 来根据模式验证 xml。我有一个带有元素的架构:

<xs:element name="link-url" type="xs:anyURL"/>

我测试了这个(部分)xml:

<a link-url="server/path"/>

我希望这个测试失败,因为link-url 不是以http:// 开头的。我尝试将 anyURI 切换为 anyURL 但这会导致异常 - 它不是有效标签。

lxml 可以做到这一点吗?模式验证有可能吗?

【问题讨论】:

  • 您的架构中是 anyURL 还是 anyURI

标签: python xml validation xsd


【解决方案1】:

(我很确定xs:anyURL 无效。XML Schema standard 将其称为anyURI。由于link-url 是一个属性,您不应该使用xs:attribute 而不是xs:element 吗? )

您可以通过在其上创建一个新的simpleType based 并在pattern 上放置一个restriction 来限制 URI。例如,

#!/usr/bin/env python2.6

from lxml import etree
from StringIO import StringIO

schema_doc = etree.parse(StringIO('''
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <xs:simpleType name="httpURL">
        <xs:restriction base="xs:anyURI">
            <xs:pattern value='https?://.+'/>
            <!-- accepts only http:// or https:// URIs. -->
        </xs:restriction>
    </xs:simpleType>

    <xs:element name="a">
        <xs:complexType>
            <xs:attribute name="link-url" type="httpURL"/>
        </xs:complexType>
    </xs:element>
    </xs:schema>
''')) #/
schema = etree.XMLSchema(schema_doc)

schema.assertValid(etree.parse(StringIO('<a link-url="http://sd" />')))
assert not schema(etree.parse(StringIO('<a link-url="server/path" />')))

【讨论】:

    猜你喜欢
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    • 1970-01-01
    相关资源
    最近更新 更多