6Feb/11Off
Write Clean XML
I've been working with XML for a while now and haven't found a solution to clean up the XML code in the written file until now. I searched for any articles about how to clean up the XML and finally fond some sample script here: http://snipplr.com/view/25657/indent-xml-using-elementtree/. I modified it a bit for my needs in XSI and it works great!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | from xml.etree import ElementTree as ET from win32com.client import constants as c from win32com.client import Dispatch as d xsi = Application log = xsi.LogMessage collSel = xsi.Selection def indent(elem, level=0): i = "\n" + level*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " if not elem.tail or not elem.tail.strip(): elem.tail = i for elem in elem: indent(elem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail = i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i def cleanxml(xml): elem = ET.fromstring(xml) indent(elem) strIndented = ET.tostring(elem) return strIndented def cleanWriteXML(strFilePath): fOpen = open(strFilePath,"r") fRead = fOpen.read() fWrite = open(strFilePath,"w") strPrettyXML = cleanxml(fRead) fWrite.write(strPrettyXML) fWrite.close() cleanWriteXML("C:\\Path\\To\\File.xml") |
