Search code examples
pythonxmlpretty-print

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?


Solution

  • 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>