Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pretty_print in etree.tostring() xml python

I am trying to print out the xml doc with pretty_print option. But it thew an error

TypeError: tostring() got an unexpected keyword argument 'pretty_print'

Am I missing something here?

def CreateXML2():
    Date = etree.Element("Date", value=time.strftime(time_format, time.localtime()));
    UserNode = etree.SubElement(Date, "User");
    IDNode = etree.SubElement(UserNode, "ID");
    print(etree.tostring(Date, pretty_print=True));
like image 549
Nogcas Avatar asked Mar 07 '12 23:03

Nogcas


People also ask

How do I print a pretty XML string in Python?

To pretty print XML in Python, we can use the xml. dom. minidom. parseString method.


2 Answers

It seems that the problem is that ElementTree library doesn't support pretty printing. A workaround, as explained here is to reparse the output string from ElementTree in another library that provides support for pretty printing.

like image 140
jcollado Avatar answered Sep 29 '22 12:09

jcollado


Have you looked at this post within StackOverflow? I think it covers what you want:

in-place prettyprint formatter

def indent(elem, level=0):
    i = "\n" + level*"  "
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + "  "
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
        for elem in elem:
            indent(elem, level+1)
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = i

That sample code was from the post and from effbot.org

Also, for additional information, you're not calling the tostring() method properly. Have a look at Python's website for more information.

like image 25
Carlos Avatar answered Sep 29 '22 10:09

Carlos