[Tutor] No Elegant XML Output in ElementTree?
Luis Galvan
cynicalairrick at gmail.com
Tue Jul 28 05:32:24 CEST 2009
Hi tutors,
Okay, so I just started to learn ElementTree (and XML processing in general)
and I just can't, for the life of me, find a way to output the XML file in
an actual hierarchic presentation. What I mean by this is that it all
outputs on a single line. For example, I create an element tree in python:
____________________________
from xml.etree.ElementTree import ElementTree, SubElement, Element
# Create example tree.
root = Element("BFTypedBinder")
root.set("binderType", "codename")
# There's no point in this loop, it's only here for kicks.
while True:
x = raw_input("Yes or No? ")
if x == "Yes":
head = SubElement(root, "sample")
title = SubElement(head, "sample2")
title.text = "Sample Text"
body = SubElement(root, "sample3")
body.set("this", "that")
body.text = "Done"
break
elif x == "No":
break
# Save output.
tree = ElementTree(root)
tree.write(xml.xml)
___________________________
Output using Notepad:
<BFTypedBinder binderType="codename"><sample><sample2>Sample
Text</sample2></sample><sample3 this="that">Done</sample3></BFTypedBinder>
If I open xml.xml in Notepad, the whole tree is printed on one line, which
isn't what I want. Of course, if I double click the file itself, it looks
normal, but I still need the data itself to look hierarchic as well (It's a
personal preference, and much more convenient when editing in a text
editor). A few months back when I was attempting to learn Minidom, it
didn't have this problem. I have looked through python.org's online
documentation on ET and there's no method, class, or function that could
help me achieve this, at least that I'm aware of.
I know I might have to write a solution myself, but before I try (which
would probably be disasterous), is there some existing built-in class in
here that can help me without having to "reinvent the wheel"?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090727/546c727e/attachment.htm>
More information about the Tutor
mailing list