0

I have an ElementTree object in Python 3.5.

I need to write it into a file with few requirements:

  • With indentation (pretty print of 2 spaces).
  • Without the version line.
  • Empty tags should appear with both opening and closing tags (for example

<sometag> </sometag> and not

<sometag/>)

EDIT

Okay, so far I have this code pp_xml = xml.dom.minidom.parseString(ET.tostring(self._root)).\ toprettyxml(indent=' ') # Remove the version line pp_xml = pp_xml[pp_xml.find('\n')+1:] ET.ElementTree(ET.fromstring(pp_xml)).write(self._out_filepath, short_empty_elements=False)

Which does almost everything I asked for, except that that empty tags appear like this: <sometag></sometag>

And I need them to be in new lines like this:

<sometag> </sometag>

  • You should post what you've tried. – code11 Sep 30 '16 at 18:33
  • Added, thanks (Too short comment). –  Sep 30 '16 at 18:38
  • Tempted to vote to close as duplicate of http://stackoverflow.com/q/749796/407651 – mzjn Sep 30 '16 at 18:46
  • It does not answer my question. Also, I can't use lxml. Only builtin modules. –  Sep 30 '16 at 18:48
  • Okay, so I can manually remove the version line (the first line) simply by `pp_xml = pp_xml[pp_xml.find('\n')+1:]` Now I only need to find a way to make 2 lines empty tags. –  Oct 01 '16 at 06:57
  • I suppose you'll have to walk through all empty elements and set their `text` property to `\n`. – mzjn Oct 02 '16 at 19:30
  • That's what I ended up doing, but it's not great because it ruins the indentation. The closing tag then appears non-indented, at the beginning of the next line. –  Oct 02 '16 at 19:36

0 Answers0