[Tutor] Pretty printing XML using LXML on Python3

SM sunithanc at gmail.com
Thu Nov 28 20:12:18 CET 2013


Hello,
I am using lxml with Python3, to generate xml code. "pretty_print" doesn't
seem to indent the generated lines.

I have installed the following lxml package:
/usr/local/lib/python3.2/dist-packages/lxml-3.2.4-py3.2-linux-x86_64.egg/lxml

The following is the example code I found on stack overflow, which runs
fine on Python2.7. But it concatenates all the lines if I run the same code
with Python3. Does anybody know what is the solution to make it work on
Python3?

from lxml import etree

# create XML
root = etree.Element('root')
root.append(etree.Element('child'))
# another child with text
child = etree.Element('child')
child.text = 'some text'
root.append(child)

# pretty string
s = etree.tostring(root, pretty_print=True)
print(s)

Run with Python:

$ python testx.py
<root>
  <child/>
  <child>some text</child>
</root>
$

Run with Python3:

$ python3 testx.py
b'<root>\n  <child/>\n  <child>some text</child>\n</root>\n'
$

Thanks in advance.
-SM
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131128/bd310ee7/attachment.html>


More information about the Tutor mailing list