python - tostring 中的 pretty_print 选项在 lxml 中不起作用

标签 python xml lxml

我正在尝试使用 XML 中的 tostring 方法来获取我的 XML 的“漂亮”版本作为字符串。 lxml 站点上的示例显示了这个示例:

>>> import lxml.etree as etree
>>> root = etree.Element("root")
>>> print(root.tag)
root
>>> root.append( etree.Element("child1") )
>>> child2 = etree.SubElement(root, "child2")
>>> child3 = etree.SubElement(root, "child3")
>>> print(etree.tostring(root, pretty_print=True))
<root>
  <child1/>
  <child2/>
  <child3/>
</root>

但是我的输出,运行那些确切的行是:

b'<root>\n  <child1/>\n  <child2/>\n  <child3/>\n</root>\n'

是不是我安装的lxml版本有问题?教程中的逐字逐句的示例不起作用似乎很奇怪。

最佳答案

字符串前面的 b 标志向您显示它是 byte string .要将其打印为 unicode 字符串(这是 Python 字符串的典型编码),您可以执行以下操作:

print(etree.tostring(root,pretty_print=True).decode())

etree.tostring 有一个允许您设置编码的标志,因此:

print(etree.tostring(root,pretty_print=True,encoding='unicode'))

两种方式都适合我。这是有关 Byte Strings 的更多信息和 Strings

关于python - tostring 中的 pretty_print 选项在 lxml 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22718101/

相关文章:

python - 使用 lxml 访问带和不带命名空间的元素

Python 类对象和 XML

python - 用于获取 <p> 内所有数据的 Xpath 表达式

python - 如何在两个 float 之间插入运算符号并计算结果?

java - Android 空指针异常与微调器

python - Python 中的级数求和

iphone - TouchXML 解析 XML 属性

xml - Findbugs XML 报告缺少排名

python - Pandas 乘以多列来制作新的 df

Python:避免数组上的嵌套循环