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

时间:2014-03-28 16:20:02

标签: 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版本是否有错误?从教程中逐字逐句的单词似乎很奇怪。

1 个答案:

答案 0 :(得分:17)

字符串前面的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 StringsStrings

的更多信息