問題描述
假設我有以下想要使用 Python 的 ElementTree
修改的 XML:
Assume that I've the following XML which I want to modify using Python's ElementTree
:
<root xmlns:prefix="URI">
<child company:name="***"/>
...
</root>
我正在對 XML 文件進行一些修改,如下所示:
I'm doing some modification on the XML file like this:
import xml.etree.ElementTree as ET
tree = ET.parse('filename.xml')
# XML modification here
# save the modifications
tree.write('filename.xml')
那么 XML 文件看起來像:
Then the XML file looks like:
<root xmlns:ns0="URI">
<child ns0:name="***"/>
...
</root>
如您所見,namepsace prefix
更改為 ns0
.我知道使用 ET.register_namespace()
提到 這里.
As you can see, the namepsace prefix
changed to ns0
. I'm aware of using ET.register_namespace()
as mentioned here.
ET.register_namespace()
的問題在于:
- 你需要知道
prefix
和URI
- 它不能與默認命名空間一起使用.
例如如果 xml 看起來像:
e.g. If the xml looks like:
<root xmlns="http://uri">
<child name="name">
...
</child>
</root>
它將被轉換為:
<ns0:root xmlns:ns0="http://uri">
<ns0:child name="name">
...
</ns0:child>
</ns0:root>
如您所見,默認命名空間更改為ns0
.
As you can see, the default namespace is changed to ns0
.
有沒有辦法用ElementTree
解決這個問題?
Is there any way to solve this problem with ElementTree
?
推薦答案
ElementTree 將替換那些未使用 ET.register_namespace
注冊的命名空間前綴.要保留命名空間前綴,您需要先注冊它,然后再將修改寫入文件.以下方法完成這項工作并在全局范圍內注冊所有命名空間,
ElementTree will replace those namespaces' prefixes that are not registered with ET.register_namespace
. To preserve a namespace prefix, you need to register it first before writing your modifications on a file. The following method does the job and registers all namespaces globally,
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
方法之前調用,這樣命名空間將保持不變,
This method should be called before ET.parse
method, so that the namespaces will remain as unchanged,
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')
這篇關于在 Python 中通過 ElementTree 解析 xml 時如何保留命名空間的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!