amitizle
amitizle

Reputation: 971

Python - print pretty XML create opening and closing tags for empty tags text

I'm writing a python application that creates an ElementTree (XML) and then writing it to a file, using minidom's toprettyxml();

final_tree = minidom.parseString(ET.tostring(root))
fdout.write(final_tree.toprettyxml(indent = '    ')

The problem is, that tags which i'm not appending any text comes out with only one tag, for example:

<sometag/>

I want it to be:

<sometag>
</sometag>

I want to do it without parsing the whole string (without regex). Is anybody familiar with such way? Thanks.

Upvotes: 2

Views: 1801

Answers (1)

Alfe
Alfe

Reputation: 59426

The behavior is hard-wired in minidom.py (have a look at writexml() method in class Element). It is not meant to be changed, but for the current implementation you can monkey-patch it like this:

from xml.dom import minidom

t = minidom.parseString('<a><b></b></a>')

def patcher(method):
  def patching(self, *args, **kwargs):
    old = self.childNodes
    try:
      if not self.childNodes:
        class Dummy(list):
          def __nonzero__(self):  # Python2
            return True
          def __bool__(self):  # Python3
            return True
        old, self.childNodes = self.childNodes, Dummy([])
      return method(self, *args, **kwargs)
    finally:
      self.childNodes = old
  return patching

t.firstChild.__class__.writexml = patcher(t.firstChild.__class__.writexml)

print t.toprettyxml()

But of course I cannot recommend such a hack.

Upvotes: 3

Related Questions