Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pretty print an XML given an XML string

I generated a long and ugly XML string with Python and I need to filter it through pretty printer to look nicer.

I found this post for python pretty printers, but I have to write the XML string to a file to be read back to use the tools, which I want to avoid if possible.

What python pretty tools are available that work on strings?

like image 284
prosseek Avatar asked Oct 20 '10 00:10

prosseek


1 Answers

Here's how to parse from a text string to the lxml structured data type.

Python 2:

from lxml import etree
xml_str = "<parent><child>text</child><child>other text</child></parent>"
root = etree.fromstring(xml_str)
print etree.tostring(root, pretty_print=True)

Python 3:

from lxml import etree
xml_str = "<parent><child>text</child><child>other text</child></parent>"
root = etree.fromstring(xml_str)
print(etree.tostring(root, pretty_print=True).decode())

Outputs:

<parent>
  <child>text</child>
  <child>other text</child>
</parent>
like image 60
monkut Avatar answered Oct 14 '22 20:10

monkut