使用 ElementTree.tostring 的 default_namespace 参数会引发错误

问题描述 投票:0回答:1

我想使用 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 文件?

python xml elementtree
1个回答
0
投票

你必须使用

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>
© www.soinside.com 2019 - 2024. All rights reserved.