【问题标题】:preserve namespaces with xml.etree使用 xml.etree 保留命名空间
【发布时间】:2020-09-20 04:44:57
【问题描述】:

在源文件的根元素中定义命名空间时,lxml 会在输出中重现所有命名空间。我需要用xml.etree 来做这件事。更好的是只输出那些使用过的,但xml.etree 并没有找到所有这些。

一种解决方案是使用root.set() 强制添加命名空间。但是,这会复制 xml.etree 找到的所有命名空间,如下所示。

适合在命令提示符中粘贴的完整示例:

import xml.etree.ElementTree as ET
try:
    from io import StringIO
except ImportError:
    from StringIO import StringIO

def get_namespaces(sourcestring):
    sourcefile = StringIO(sourcestring)
    return dict(
        [node for _, node in ET.iterparse(sourcefile, events=['start-ns'])])

ET._namespace_map = dict()  # remove any previously registered namespaces
sourcetext = (
    '<desc xmlns="uri_a" xmlns:b="uri_b" xmlns:c="uri_c"'
    ' b:foo="c:bar">a</desc>')
source = ET.fromstring(sourcetext)
namespaces = get_namespaces(sourcetext)
for prefix, uri in namespaces.items():
    ET.register_namespace(prefix, uri)
    if prefix:
        tag = 'xmlns:' + prefix
    else:
        tag = 'xmlns'
    source.set(tag, uri)

print(ET.tostring(source, encoding='unicode'))

导致我的应用程序失败的结果:

<desc xmlns="uri_a" xmlns:b="uri_b" xmlns="uri_a" xmlns:b="uri_b" xmlns:c="uri_c" b:foo="c:bar">a</desc>

这类似于Forcing xml.etree to output "unused" namespaces,但命名空间来自源文件,因此 Python 代码不知道它们。

【问题讨论】:

    标签: python xml namespaces elementtree


    【解决方案1】:

    首先,在不添加缺少的命名空间的情况下生成输出。获取从该输出中找到的命名空间。然后,通过添加未找到的命名空间来生成最终输出。

    def add_namespaces_not_found(root):
        result_with_namespaces_found = ET.tostring(root, encoding='unicode')
        namespaces_found = get_namespaces(result_with_namespaces_found)
        for prefix, uri in namespaces.items():
            if prefix not in namespaces_found:
                if prefix:
                    tag = 'xmlns:' + prefix
                else:
                    tag = 'xmlns'
                root.set(tag, uri)
    

    结果:

    <desc xmlns="uri_a" xmlns:b="uri_b" xmlns:c="uri_c" b:foo="c:bar">a</desc>
    

    欢迎使用不需要生成两次输出的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多