Reputation: 189866
I need to output XML from python in a very minimalist way:
At this point I'm using print statements to explicitly print out angle-bracket tags, and the only thing really stopping me is escaping text within a tag, which I do not know how to do.
Any suggestions?
update: Is there anything like Java's StAX XMLStreamWriter for Python? I may have a large XML document to produce, and I don't need (or want) to hold the entire document in memory.
update #2: I also need to escape random unicode or non-ASCII characters in the text besides <
, >
and &
.
Upvotes: 1
Views: 3879
Reputation: 189866
Well, it looks like SAX isn't that hard to use after all. Here's an example.
xmltest.py:
import xml.sax.xmlreader
import xml.sax.saxutils
def testJunk(file, e2content):
attr0 = xml.sax.xmlreader.AttributesImpl({})
x = xml.sax.saxutils.XMLGenerator(file)
x.startDocument()
x.startElement("document", attr0)
x.startElement("element1", attr0)
x.characters("bingo")
x.endElement("element1")
x.startElement("element2", attr0)
x.characters(e2content)
x.endElement("element2")
x.endElement("document")
x.endDocument()
tested:
>>> import xmltest
>>> xmltest.testJunk(open("test.xml","w"), "wham < 3!")
produces:
<?xml version="1.0" encoding="iso-8859-1"?>
<document><element1>bingo</element1><element2>wham < 3!</element2></document>
Upvotes: 4
Reputation: 178179
ElementTree comes with Python 2.6:
from xml.etree import ElementTree as ET
root = ET.Element('root')
sub = ET.SubElement(root,'sub')
sub.text = 'Hello & Goodbye'
tree = ET.ElementTree(root)
tree.write('out.xml')
# OR
ET.dump(root)
<root><sub>Hello & Goodbye</sub></root>
Upvotes: 2
Reputation: 10309
If task is as simple, minidom may suffice. Here goes short example:
from xml.dom.minidom import Document
# create xml document
document = Document()
# create root element
root = document.createElement("root")
document.appendChild(root)
# create child element
child = document.createElement("child")
child.setAttribute("tag", "test")
root.appendChild(child)
# insert some text
atext = document.createTextNode("Foo bar")
child.appendChild(atext)
# print created xml
print(document.toprettyxml(indent=" "))
Upvotes: 2