在@bobince的答案和这两个帮助下(设置属性顺序,覆盖模块方法)
我设法修复了这只猴子的脏污,建议使用另一个模块更好地处理这种情况,但是在这种情况下是不可能的:
# =======================================================================# Monkey patch ElementTreeimport xml.etree.ElementTree as ETdef _serialize_xml(write, elem, encoding, qnames, namespaces): tag = elem.tag text = elem.text if tag is ET.Comment: write("<!--%s-->" % ET._enpre(text, encoding)) elif tag is ET.ProcessingInstruction: write("<?%s?>" % ET._enpre(text, encoding)) else: tag = qnames[tag] if tag is None: if text: write(ET._escape_cdata(text, encoding)) for e in elem: _serialize_xml(write, e, encoding, qnames, None) else: write("<" + tag) items = elem.items() if items or namespaces: if namespaces: for v, k in sorted(namespaces.items(), key=lambda x: x[1]): # sort on prefix if k: k = ":" + k write(" xmlns%s="%s"" % ( k.enpre(encoding), ET._escape_attrib(v, encoding) )) #for k, v in sorted(items): # lexical order for k, v in items: # Monkey patch if isinstance(k, ET.QName): k = k.text if isinstance(v, ET.QName): v = qnames[v.text] else: v = ET._escape_attrib(v, encoding) write(" %s="%s"" % (qnames[k], v)) if text or len(elem): write(">") if text: write(ET._escape_cdata(text, encoding)) for e in elem: _serialize_xml(write, e, encoding, qnames, None) write("</" + tag + ">") else: write(" />") if elem.tail: write(ET._escape_cdata(elem.tail, encoding))ET._serialize_xml = _serialize_xmlfrom collections import OrderedDictclass OrderedXMLTreeBuilder(ET.XMLTreeBuilder): def _start_list(self, tag, attrib_in): fixname = self._fixname tag = fixname(tag) attrib = OrderedDict() if attrib_in: for i in range(0, len(attrib_in), 2): attrib[fixname(attrib_in[i])] = self._fixtext(attrib_in[i+1]) return self._target.start(tag, attrib)# =======================================================================
然后在您的代码中:
tree = ET.parse(pathToFile, OrderedXMLTreeBuilder())
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)