将Python XML ElementTree转换为String

use*_*003 7 python xml elementtree

我需要在更改后将XML ElementTree转换为String.这是toString部分无法正常工作.

import xml.etree.ElementTree as ET

tree = ET.parse('my_file.xml')
root = tree.getroot()

for e in root.iter('tag_name'):
    e.text = "something else" # This works

# Now I want the the complete XML as a String with the alteration
Run Code Online (Sandbox Code Playgroud)

我已经尝试了以下各种版本的版本,ET或ElementTree作为各种名称,并导入toString等等,

s = tree.tostring(ET, encoding='utf8', method='xml')
Run Code Online (Sandbox Code Playgroud)

我已经看到将Python Python ElementTree转换为字符串和其他一些,但我不确定如何将它应用于我的示例.

Ste*_*ica 9

我如何转换ElementTree.Element为字符串?

对于 Python 3:

xml_str = ElementTree.tostring(xml, encoding='unicode')
Run Code Online (Sandbox Code Playgroud)

对于 Python 2:

xml_str = ElementTree.tostring(xml, encoding='utf-8')
Run Code Online (Sandbox Code Playgroud)

为了与 Python 2 和 3 兼容:

xml_str = ElementTree.tostring(xml).decode()
Run Code Online (Sandbox Code Playgroud)

示例用法

from xml.etree import ElementTree

xml = ElementTree.Element("Person", Name="John")
xml_str = ElementTree.tostring(xml).decode()
print(xml_str)
Run Code Online (Sandbox Code Playgroud)

输出:

<Person Name="John" />
Run Code Online (Sandbox Code Playgroud)

解释

尽管顾名思义,ElementTree.tostring()在 Python 2 和 3 中默认返回一个字节。这是 Python 3 中的一个问题,它使用 Unicode 来表示字符串

在 Python 2 中,您可以将str类型用于文本和二进制数据。不幸的是,这两个不同概念的融合可能会导致脆弱的代码,这些代码有时适用于任何一种数据,有时则不起作用。[...]

为了使文本和二进制数据之间的区别更清晰、更明显,[Python 3] 使文本和二进制数据具有不同的类型,不能盲目混合在一起

来源:将Python 2 代码移植到 Python 3

如果我们知道正在使用的 Python 版本,我们可以将编码指定为unicodeor utf-8。否则,如果我们需要与 Python 2 和 3 兼容,我们可以使用decode()转换为正确的类型。

作为参考,我已经包含了.tostring()Python 2 和 Python 3 之间的结果比较。

ElementTree.tostring(xml)
# Python 3: b'<Person Name="John" />'
# Python 2: <Person Name="John" />

ElementTree.tostring(xml, encoding='unicode')
# Python 3: <Person Name="John" />
# Python 2: LookupError: unknown encoding: unicode

ElementTree.tostring(xml, encoding='utf-8')
# Python 3: b'<Person Name="John" />'
# Python 2: <Person Name="John" />

ElementTree.tostring(xml).decode()
# Python 3: <Person Name="John" />
# Python 2: <Person Name="John" />
Run Code Online (Sandbox Code Playgroud)

感谢Martijn Peters指出strPython 2 和 3 之间的数据类型发生了变化。


为什么不使用 str()?

在大多数情况下, usingstr()是将对象转换为字符串的“规范”方式。不幸的是,使用它Element返回对象在内存中的位置作为十六进制字符串,而不是对象数据的字符串表示。

from xml.etree import ElementTree

xml = ElementTree.Element("Person", Name="John")
print(str(xml))  # <Element 'Person' at 0x00497A80>
Run Code Online (Sandbox Code Playgroud)


Ste*_*ney 6

这应该工作: -

xmlstr = ET.tostring(root, encoding='utf8', method='xml')
Run Code Online (Sandbox Code Playgroud)

  • 讽刺的是,`tostring` 生成 python `bytes` (2认同)
  • 由于`str`的​​更改,因此在Python 3中不起作用。[使用`ET.tostring(root).decode()`或`ET.tostring(root,encoding ='unicode',method ='xml ')`](/sf/answers/3407004961/)。 (2认同)