newline - how to build xml file in python, with formatting -


i'm trying build xml file in python can write out file, i'm getting complications new lines , tabbing etc...

i cannot use module - because im using cut down version of python 2. must in pure python.

for instance, how possible create xml file type of formatting, keeps new lines , tabs (whitespace)?

e.g.

<?xml version="1.0" encoding="utf-8"?> <myfiledata>     <mydata>             blahblah     </mydata> </myfiledata> 

i've tried enclosing each line

'    <myfiledata>' +\n '                blahblah' +\n 

etc.

however, output im getting script not close how looks in python file, there white space , new lines arent working.

is there definitive way this? rather editing file looks end - clarity sake...

you can use xmlgenerator saxutils generate xml , xml.dom.minidom parse , print pretty xml (both modules standard library in python 2).

sample code creating xml , pretty-printing it:

from __future__ import print_function xml.sax.saxutils import xmlgenerator import io import xml.dom.minidom  def pprint_xml_string(s):     """pretty-print xml string minidom"""     parsed = xml.dom.minidom.parse(io.bytesio(s))     return parsed.toprettyxml()  # create xml file in-memory: fp = io.bytesio() xg = xmlgenerator(fp)  xg.startdocument() xg.startelement('root', {})  xg.startelement('subitem', {}) xg.characters('text content') xg.endelement('subitem')  xg.startelement('subitem', {}) xg.characters('text content subitem') xg.endelement('subitem')  xg.endelement('root') xg.enddocument()  # pretty-print xml_string = fp.getvalue() pretty_xml = pprint_xml_string(xml_string) print(pretty_xml) 

output is:

<?xml version="1.0" ?> <root>     <subitem>text content</subitem>     <subitem>text content subitem</subitem> </root> 

note text content elements (wrapped in <subitem> tags) aren't indented because doing change content (xml doesn't ignore whitespace html does).


Comments