pretty_print option in tostring not working in lxml

江枫思渺然 提交于 2021-02-15 11:35:17

问题


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'

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.


回答1:


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())

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



来源:https://stackoverflow.com/questions/22718101/pretty-print-option-in-tostring-not-working-in-lxml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!