This article explains how to parse XML through ElementTree, get the son node, insert the Son node, manipulate the attributes, beautify the XML
.
1. The introduction of the library requires 3 classes, elementtree,element, and a wrapper class to create subclasses subelement from Xml.etree.ElementTree import ElementTree from Xml.etree.ElementTree Import Element from xml.etree.ElementTree import subelement as SE 2. Read and parse tree = ElementTree ( File=xmlfile) root = Tree.getroot () After reading, the tree is the type of ElementTree, get the XML root node to use the Getroot () method; XML sample file: code as follows: & Lt;item sid= ' 1712 ' name = ' Big cc ' > <a id=1></a> <a id=2></a> </item> 3 Get a son node to find all the child nodes of the element: Code as follows: Aarry = Item.findall (' A ') can also use GetChildren (): Childs = item.getch Ildren () for subitem in Childs: print subitem.get (' id ')   ; 4. Insert Son node method one: Copy code code is as follows: item = Element ("item", {' Sid ': ' 1713 ', ' name ': ' Ityouhui '}) ro Ot.append (item) Method Two: The code is as follows: SE (Root, ' item ', {' sid ': ' 1713 ', ' name ': ' Ityouhui '}) Fayi The advantage is that you can continue with the item after inserting. The second method is simple in writing, in which SE is subelement, made a statement at the introduction; 5.An Action property gets the value of an attribute of an element (eg: Gets the item's name) code as follows: Print root.find (' Item/name '). Text print item.get (' name ') Get element All attributes copy code code as follows: Print Item.items () # [(' Sid ', ' 1712 '), (' Name ', ' Big cc ')] Print item.at Trib # {' sid ': ' 1712 ', ' name ': ' Big cc '} 6. To beautify XML before writing, incoming root calls this function, the written XML file format is neat and beautiful: & nbsp Code as follows: Indent (root) book.write (xmlfile, ' utf-8 ') code as follows: # get pretty look def indent (Elem, level=0): i = "n" + level* " " If Len (elem): if not E Lem.text or Not Elem.text.strip (): Elem.text = i + " " &NBSP ; for E on Elem: indent (e, level+1) if not e.ta Il or not e.tail.strip (): E.tail = i if level and (not Elem.tail O R not Elem.tail.strip ()): Elem.tail = i return elem