简体   繁体   中英

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));

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM