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));
Nogcas
  • 91
  • 1
  • 1
  • 5
  • 5
    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. – Francis Avila Mar 07 '12 at 23:11
  • 1
    I used xml.etree not lxml. So the xml.etree does not have pretty_print in its etree.tostring()?? – Nogcas Mar 08 '12 at 04:22
  • No, it does not. Read [the documentation](http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.tostring), or even just run `help(etree.tostring)` in a console. – Francis Avila Mar 08 '12 at 04:47
  • Does this answer your question? [Pretty printing XML in Python](https://stackoverflow.com/questions/749796/pretty-printing-xml-in-python) – outis Jul 01 '21 at 22:44

2 Answers2

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.

jcollado
  • 39,419
  • 8
  • 102
  • 133
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.

Community
  • 1
  • 1
Carlos
  • 1,897
  • 3
  • 19
  • 37