Python is pretty XML printer for XML string

I am generating a long and ugly XML string with python and I need to filter it through a pretty printer in order to look better.

I found this post for good python printers, but I need to write an XML string to a file that needs to be read in order to use the tools that I want to avoid, if possible.

What available python tools that work in a string are available?

+7
python xml pretty-print
source share
2 answers

Here's how to parse from text string to 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> 
+15
source share

I use the lxml library, and there it is as simple as

 >>> print(etree.tostring(root, pretty_print=True)) 

You can perform this operation with any etree , which you can either generate programmatically or read from a file.

If you are using the DOM from PyXML, this

 import xml.dom.ext xml.dom.ext.PrettyPrint(doc) 

This prints to standard output unless you specify an alternate stream.

http://pyxml.sourceforge.net/topics/howto/node19.html

To use the mini-disk, you want to use the toprettyxml() function.

http://docs.python.org/library/xml.dom.minidom.html#xml.dom.minidom.Node.toprettyxml

+5
source share

All Articles