Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pretty_print option in tostring not working in lxml

Tags:

python

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'

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.

like image 890
lanteau Avatar asked Mar 28 '14 16:03

lanteau


1 Answers

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

like image 91
Adam Smith Avatar answered Oct 02 '22 08:10

Adam Smith