tostring中的pretty_print选项在lxml中不起作用 [英] pretty_print option in tostring not working in lxml
问题描述
我试图在XML中使用tostring方法来获取XML的漂亮"版本作为字符串.lxml站点上的示例显示了以下示例:
I'm trying to use the tostring method in XML to get a "pretty" version of my XML as a string. The example on the lxml site shows this example:
>>> 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>
不过,我的输出结果是:
However my output, running those exact lines is:
b'<root>\n <child1/>\n <child2/>\n <child3/>\n</root>\n'
我安装的lxml版本中是否存在错误?教程中的逐字示例似乎不起作用.
Is there a bug in the version of lxml I have installed? It seems odd the word for word example from the tutorial is not working.
推荐答案
the b
flag in front of the string shows you that it's a byte string. To print that as a unicode string (which is the typical encoding for a Python string), you can do:
print(etree.tostring(root,pretty_print=True).decode())
或 etree.tostring
具有用于设置编码的标志,因此:
or etree.tostring
has a flag that allows you to set the encoding, so:
print(etree.tostring(root,pretty_print=True,encoding='unicode'))
这两种方法都对我有效.以下是有关字节字符串和
Either way works for me. Here's more information on Byte Strings and Strings
这篇关于tostring中的pretty_print选项在lxml中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!