我想使用 ElementTree 修改 XML 文档并保持其可比性,我希望新文件中具有与旧文件中相同的命名空间前缀。
但是,
default_namespace=
和 ET.tostring
的 ET.write
参数即使对于简单的文档也会导致错误。
这是一个例子:
示例
test.xml
文件:
<?xml version="1.0"?>
<test xmlns="http://www.example.com/blabla/">
<item name="first" />
</test>
测试:
Python 3.11.5 (tags/v3.11.5:cce6ba9, Aug 24 2023, 14:38:34) [MSC v.1936 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import xml.etree.ElementTree as ET
>>> xml = ET.parse("test.xml")
>>> ET.tostring(xml, default_namespace="http://www.example.com/blabla/")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python311\Lib\xml\etree\ElementTree.py", line 1098, in tostring
ElementTree(element).write(stream, encoding,
File "C:\Python311\Lib\xml\etree\ElementTree.py", line 741, in write
qnames, namespaces = _namespaces(self._root, default_namespace)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python311\Lib\xml\etree\ElementTree.py", line 856, in _namespaces
add_qname(key)
File "C:\Python311\Lib\xml\etree\ElementTree.py", line 833, in add_qname
raise ValueError(
ValueError: cannot use non-qualified names with default_namespace option
有没有办法按照显示的方式编写 XML 文件?
你必须使用
register_namespace()
:
另请参阅 xml.etree.ElementTree 文档。
import xml.etree.ElementTree as ET
xml_ = """\
<?xml version="1.0"?>
<test xmlns="http://www.example.com/blabla/">
<item name="first" />
</test>"""
root = ET.fromstring(xml_)
ET.register_namespace('','http://www.example.com/blabla/')
tree = ET.ElementTree(root)
ET.indent(tree, space=' ')
tree.write("out.xml", xml_declaration=True, encoding='utf-8')
ET.dump(tree)
输出:
<test xmlns="http://www.example.com/blabla/">
<item name="first" />
</test>