1. Introduction of the Library
Need to use 3 classes, Elementtree,element, and set up subclasses of the wrapper class subelement
From Xml.etree.ElementTree import ElementTree
From Xml.etree.ElementTree import Element
From Xml.etree.ElementTree import subelement as SE
2. Read into and parse
Tree = ElementTree (file=xmlfile)
root = Tree.getroot ()
After reading, the tree is the type of ElementTree, the XML root node is obtained using the Getroot () method;
XML sample file:
Copy Code code as follows:
<item sid= ' 1712 ' name = ' Big cc ' >
<a id=1></a>
<a id=2></a>
</item>
3. Get son knot
Find all child nodes of an element:
Copy Code code as follows:
Aarry = Item.findall (' a ')
You can also use GetChildren ():
Childs = Item.getchildren ()
For subitem in Childs:
Print subitem.get (' id ')
4. Insert a son knot
Method One:
Copy Code code as follows:
Item = Element ("item", {' Sid ': ' 1713 ', ' name ': ' Ityouhui '})
Root.append (item)
Method Two:
Copy Code code as follows:
SE (Root, ' item ', {' sid ': ' 1713 ', ' name ': ' Ityouhui '})
The benefit of Fayi is that you can continue to work on the item after you insert it. The second method is simple in writing, in which SE is subelement, which makes a statement at the introduction place;
5. Operation Properties
Gets an attribute value for an element (eg: Gets the item's name)
Copy Code code as follows:
Print Root.find (' Item/name '). Text
Print item.get (' name ')
Get all attributes of element
Copy Code code as follows:
Print Item.items () # [(' Sid ', ' 1712 '), (' Name ', ' Big cc ')]
Print Item.attrib # {' sid ': ' 1712 ', ' name ': ' Big cc '}
6. Beautify XML
Before writing, incoming root calls this function, and the XML file is written in a neat and beautiful format:
Copy Code code as follows:
Indent (Root)
Book.write (xmlfile, ' utf-8 ')
Copy code code as follows:
# # Get Pretty look
def indent (Elem, level=0):
i = "\ n" + level* ""
If Len (elem):
If not elem.text or not Elem.text.strip ():
Elem.text = i + ""
For E in Elem:
Indent (e, level+1)
If not e.tail or not E.tail.strip ():
E.tail = i
If level and (not elem.tail or not Elem.tail.strip ()):
Elem.tail = i
return Elem