【问题标题】:python lxml attribute namespaces within namespaces命名空间内的python lxml属性命名空间
【发布时间】:2018-10-18 20:30:19
【问题描述】:

在我正在查看的文件上传文档中,它需要在 xml 文件的开头使用这个特定的标签:

<oclcPersonas xmlns="http://worldcat.org/xmlschemas/IDMPersonas-2.2" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://worldcat.org/xmlschemas/IDMPersonas-2.2 IDMPersonas-2.2.xsd">

我正在尝试使用 lxml.etree 库来解决这个问题。

我见过的许多示例都有一个初始级别的命名空间,用于覆盖xmlns:xsi 部分的属性:

namespace_map = {
        None: persona_namespace,
        'xsi': "http://www.w3.org/2001/XMLSchema-instance"}

但是第二部分出现了两个问题xsi:schemaLocation

1) 如何使用 lxml 完成二级命名空间?

2) 如何允许命名空间包含空格而不收到错误 (http://worldcat.org/xmlschemas/IDMPersonas-2.2 IDMPersonas-2.2.xsd)

【问题讨论】:

    标签: python lxml xml-namespaces


    【解决方案1】:

    在您的示例 XML 中,您有:

    要使用 lxml 构建此元素,您需要使用带有花括号的完全限定名称(James Clark 表示法)。

    首先定义一个存储命名空间映射的字典:

    # your namespaces
    p_url = "http://worldcat.org/xmlschemas/IDMPersonas-2.2"
    xsi_url = "http://www.w3.org/2001/XMLSchema-instance"
    NS = {None: p_url, 'xsi': xsi_url}
    

    为了构建完全限定的命名空间,您可以定义前缀:

    # tag prefixes
    P = '{' + p_url + '}'
    XSI = '{' + xsi_url + '}'
    

    然后你可以定义标签名称和属性:

    # tag names and attributes
    root_tag = P + 'oclcPersonas'
    attrs = {
        XSI + 'schemaLocation':
        "http://worldcat.org/xmlschemas/IDMPersonas-2.2 IDMPersonas-2.2.xsd"
    }
    

    根元素可以如下创建:

    # element
    root = etree.Element(root_tag, attrib=attrs, nsmap=NS)
    

    你应该有你的元素:

    print(etree.tounicode(root))
    

    回答你的问题:

    2) 如何允许命名空间包含空格而不收到错误 (http://worldcat.org/xmlschemas/IDMPersonas-2.2 IDMPersonas-2.2.xsd)

    这不是命名空间,这是schemaLocation 属性的值。一个简单的字符串。

    【讨论】:

    • 非常感谢!完美运行
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    • 2018-07-10
    相关资源
    最近更新 更多