Writing XML from Python: Python.NET equivalent of XmlTextWriter?

I have IronPython code that uses an XmlTextWriter that 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 through Python implementations (CPython, IronPython and Jython). Is there a Python streaming XML writer that I can use for this, without using any print statements, or to build a whole DOM tree before writing it to a file?

+3
source share
3 answers

loxun, : http://pypi.python.org/pypi/loxun/. CPython 2.5 Jython 2.5, IronPython.

:

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()

:

<?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>

, API , Unicode .

+3

.NET, , , Python SAX parser ( , XMLGenerator - ).

+2

XML Python (code )

+2
source

Source: https://habr.com/ru/post/1710925/


All Articles