tags:

views:

122

answers:

3

Is there any way other than creating a method myself to write XML using python which are easily readable? xMLFile.write(xmlDom.toxml()) does create proper xml but reading them is pretty difficult. I tried toprettyxml but doesn't seem like it does much. e.g. following is what I would consider a human readable xml:

<myroot>
    <ent1
        att1="val1"
        att2="val2"
        att3="val3"
    />
    <ent2>
        <ent3
            att1="val1"
            att2="val2"
        />
    </ent2>
</myroot>

Solutions summary from the below responses:
1) If you just need to occassionaly read it for debugging then instead of formatting the xml while writing use xmllint or an xml editor to read it. Or
2) Use a library like Beautiful Soup. Or
3) Write your own method

A: 

Unfortunately, XML readability by humans was not a design goal. Contrariwise, BeautifulStoneSoup makes an effort to prettify XML. It isn't great, but it is better than nothing.

msw
A: 

Write your own method for formatting the xml doc. For example this will produce the format of your example XML string:

rep={" ":" \n",
     "/>":"\n/>"}

outStr=xmlDom.toxml()

for k in rep:
        outStr=outStr.replace(k, rep[k])
zoli2k
+3  A: 
print lxml.etree.tostring(root_node, pretty_print=True)
Walter