3

I have some IronPython code which makes use of XmlTextWriter which allows me to write code like

self.writer = System.Xml.XmlTextWriter(filename, None)
self.writer.Formatting = Formatting.Indented
self.writer.WriteStartElement(name)
self.writer.WriteString(str(text))
self.writer.WriteEndElement()

...

self.writer.Close()

I would like to make my code portable across Python implementations (CPython, IronPython and Jython). Is there a streaming Python XML writer I can use for this without needing to use either print statements, or to construct a whole DOM tree before writing it out to file?

Rob Smallshire
  • 1,450
  • 1
  • 15
  • 22
  • Is this the same thing as http://stackoverflow.com/questions/1019895/serialize-python-dictionary-to-xml – S.Lott Jun 20 '09 at 20:19
  • @S.Lott No it isn't. The question you refer to is about serialising Python data structures directly to XML. This question is about producing a specific XML form from Python. – Rob Smallshire Jun 18 '11 at 05:59

3 Answers3

3

I wrote a module named loxun to do just that: http://pypi.python.org/pypi/loxun/. It runs with CPython 2.5 and Jython 2.5, but I never tried it with IronPython.

Example usage:

with open("...", "wb") as out:
  xml = XmlWriter(out)
  xml.addNamespace("xhtml", "http://www.w3.org/1999/xhtml")
  xml.startTag("xhtml:html")
  xml.startTag("xhtml:body")
  xml.text("Hello world!")
  xml.tag("xhtml:img", {"src": "smile.png", "alt": ":-)"})
  xml.endTag()
  xml.endTag()
  xml.close()

And the result:

<?xml version="1.0" encoding="utf-8"?>
<xhtml:html xlmns:xhtml="http://www.w3.org/1999/xhtml">
  <xhtml:body>
    Hello world!
    <xhtml:img alt=":-)" src="smile.png" />
  </xhtml:body>
</xhtml:html>

Among other features, it detects missalligned tags while you write, uses a streaming API with a small memory footprint, supports Unicode and allows to disable pretty printing.

roskakori
  • 3,139
  • 1
  • 30
  • 29
2

I've never used the .NET implementation you're talking about, but it sounds like the closest you're going to get is Python's SAX parser (specifically, the XMLGenerator class -- some sample code here).

Sasha Chedygov
  • 127,549
  • 26
  • 102
  • 115
2

I wrote a tool to facilitate XML generation from Python (code and tutorial)

Bill Zeller
  • 1,336
  • 1
  • 9
  • 13
  • "I a tool"? What does that mean? ;) – Sasha Chedygov Jun 21 '09 at 03:57
  • Most elegant. Can you provide an example of how this would be used in the case where I don't know the element names until run time? – Rob Smallshire Jun 21 '09 at 11:33
  • It assumes the element names are known so it sounds like it doesn't solve your problem. (Well, you could write something like x = XMLegant() element_name = "root" el = getattr(x, element_name) but that seems to defeat the point.) – Bill Zeller Jun 21 '09 at 20:06