pretty_print in etree.tostring() xml python
Asked Answered
N

2

7

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));
Nucellus answered 7/3, 2012 at 23:4 Comment(4)
Are you sure you are using lxml.etree (lxml library) and not xml.etree.ElementTree (the built-in ElementTree Python library)? The former has a pretty_print argument, but the latter does not.Mythopoeic
I used xml.etree not lxml. So the xml.etree does not have pretty_print in its etree.tostring()??Nucellus
No, it does not. Read the documentation, or even just run help(etree.tostring) in a console.Mythopoeic
Does this answer your question? Pretty printing XML in PythonAdditament
I
3

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.

Indihar answered 7/3, 2012 at 23:12 Comment(2)
@mastashake57 Oh, yes, there are a lot of race conditions in this site.Indihar
The link is not working for me, is it working for someone?Dry
M
2

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.

Martingale answered 7/3, 2012 at 23:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.