使用python的minidom模块格式化、对齐、换行、整理xml文件

#!/usr/bin/python3
 
# coding=utf-8
from xml.dom import minidom    
import xml
 
def fixed_writexml(self, writer, indent="", addindent="", newl=""): 
    # indent = current indentation 
    # addindent = indentation to add to higher levels 
    # newl = newline string 
    writer.write(indent+"<" + self.tagName) 
 
    attrs = self._get_attributes() 
    a_names = attrs.keys() 
    a_names.sort() 
 
    for a_name in a_names: 
        writer.write(" %s=\"" % a_name) 
        minidom._write_data(writer, attrs[a_name].value) 
        writer.write("\"") 
    if self.childNodes: 
        if len(self.childNodes) == 1 and self.childNodes[0].nodeType == minidom.Node.TEXT_NODE: 
            writer.write(">") 
            self.childNodes[0].writexml(writer, "", "", "") 
            writer.write("</%s>%s" % (self.tagName, newl)) 
            return 
        writer.write(">%s"%(newl)) 
        for node in self.childNodes: 
            if node.nodeType is not minidom.Node.TEXT_NODE: 
                node.writexml(writer,indent+addindent,addindent,newl) 
        writer.write("%s</%s>%s" % (indent,self.tagName,newl)) 
    else: 
        writer.write("/>%s"%(newl)) 
 
minidom.Element.writexml = fixed_writexml

 

posted @ 2017-12-20 10:40  Gnnnny  阅读(2450)  评论(0编辑  收藏  举报