繁体   English   中英

在 Python 中通过 ElementTree 解析 xml 时如何保留命名空间

[英]How to preserve namespaces when parsing xml via ElementTree in Python

假设我有以下 XML,我想使用 Python 的ElementTree修改它:

<root xmlns:prefix="URI">
  <child company:name="***"/>
  ...
</root> 

我正在对 XML 文件进行一些修改,如下所示:

import xml.etree.ElementTree as ET
tree = ET.parse('filename.xml')
# XML modification here
# save the modifications
tree.write('filename.xml')

然后 XML 文件看起来像:

<root xmlns:ns0="URI">
  <child ns0:name="***"/>
  ...
</root>

如您所见,namepsace prefix更改为ns0 我知道使用这里提到的ET.register_namespace()

ET.register_namespace()的问题在于:

  1. 您需要知道prefixURI
  2. 它不能与默认命名空间一起使用。

例如,如果 xml 看起来像:

<root xmlns="http://uri">
    <child name="name">
    ...
    </child>
</root>

它将被转换为类似的东西:

<ns0:root xmlns:ns0="http://uri">
    <ns0:child name="name">
    ...
    </ns0:child>
</ns0:root>

如您所见,默认命名空间已更改为ns0

有没有办法用ElementTree解决这个问题?

ElementTree 将替换那些未使用ET.register_namespace注册的命名空间前缀。 要保留命名空间前缀,您需要在将修改写入文件之前先注册它。 以下方法完成工作并全局注册所有命名空间,

def register_all_namespaces(filename):
    namespaces = dict([node for _, node in ET.iterparse(filename, events=['start-ns'])])
    for ns in namespaces:
        ET.register_namespace(ns, namespaces[ns])

这个方法应该在ET.parse方法之前ET.parse ,这样命名空间将保持不变,

import xml.etree.ElementTree as ET
register_all_namespaces('filename.xml')
tree = ET.parse('filename.xml')
# XML modification here
# save the modifications
tree.write('filename.xml')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM