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));
To pretty print XML in Python, we can use the xml. dom. minidom. parseString method.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With