# _ * _ Encoding: UTF-8 _ * _ # -- seanyxie 2012.3.23 -- #=== XML code example for minidom operation import xmlfrom XML. dom import minidomimport codecs # = since the default writexml () function of minidom reads an XML file, it is modified and then written again. If newl = '\ n' is added ', will Write redundant rows in the original XML #== so use the following function to replace 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_writexmldef opxml (): #===== impl = xml from an empty XML document. dom. getdomimplementation () dom = impl. createdocument (none, 'all _ students ', none) root = dom.doc umentelement # -- create a node and add it to student = Dom under root. createelement ('student ') root. appendchild (student) # -- create a subnode and set the attribute namee = Dom. createelement ('name') value = u'eason Chan 'namee. setattribute ("ATTR", value) Namen = Dom. createtextnode (value) namee. appendchild (Namen) student. appendchild (namee) # -- write to the file. If Unicode occurs, specify the file encoding F = codecs. open ('1. XML ', 'w', 'utf-8') Dom. writexml (F, addindent = '', newl = '\ n', encoding = 'utf-8') F. close () #==== process an existing XML document dom = xml. dom. minidom. parse ("1.xml") root = dom.doc umentelement # -- reset the attribute # --- return all nodes whose node name is student allnodes = Dom. getelementsbytagname ('student ') value = u'wang Lihong' for node in allnodes: node. setattribute ('name', value) # -- delete the node attribute for node in allnodes: node. removeattribute ('name') # -- each node has attributes such as nodetype, nodename, and nodevaulue # -- for textnode, you can use the following content for text :. data Attribute print node. nodetype, node. nodevalue # -- you can also delete the node root. removechild (node) F = codecs. open ('1. XML ', 'w', 'utf-8') Dom. writexml (F, addindent = '', newl = '\ n', encoding = 'utf-8') F. close () If _ name __= = '_ main _': opxml ()
The above Code contains common operations for mini Dom to operate XML in Python