Benutzer-Werkzeuge

Webseiten-Werkzeuge


scripting:python:python-xml

Nice XML with Python

The following code generates nice xml without extra dependencies like pyxml.

from StringIO import StringIO
from string import strip
 
def fixed_writexml(self, writer, indent="", addindent="", newl=""):
    # indent = current indentation
    # addindent = indentation to add to higher levels
    # newl = newline string
    writer.write(indent+"<" + self.tagName)
 
    attrs = self._get_attributes()
    a_names = attrs.keys()
    a_names.sort()
 
    for a_name in a_names:
        writer.write(" %s=\"" % a_name)
        xml.dom.minidom._write_data(writer, attrs[a_name].value)
        writer.write("\"")
    if self.childNodes:
        if len(self.childNodes) == 1 \
          and self.childNodes[0].nodeType == xml.dom.minidom.Node.TEXT_NODE:
            writer.write(">")
            self.childNodes[0].writexml(writer, "", "", "")
            writer.write("</%s>%s" % (self.tagName, newl))
            return
        writer.write(">%s" % newl)
        for node in self.childNodes:
            fixed_writexml(node, writer,indent+addindent,addindent,newl)
        writer.write("%s</%s>%s" % (indent,self.tagName,newl))
    else:
        writer.write("/>%s"%(newl))
 
def fixed_toprettyxml(self, indent="", addindent="\t", newl="\n"):
    # indent = current indentation
    # addindent = indentation to add to higher levels
    # newl = newline string
    writer = StringIO()
    fixed_writexml(self, writer, indent, addindent, newl)
    return writer.getvalue()

To use this just call fixed_toprettyxml and your xml output will have the nice looking xml-structure:

<foo>
  <foob>
    <fooba>foobar</fooba>
  </foob>
</foo>

Comments



L K Q V G

Linkbacks

Sende manuelle Trackbacks an folgende URL:http://andrwe.org/lib/plugins/linkback/exe/trackback.php/scripting:python:python-xml
scripting/python/python-xml.txt · Zuletzt geändert: 2010/11/23 19:25 (Externe Bearbeitung)

Seiten-Werkzeuge