1. Introduction of libraries
You need to use 3 classes, elementtree,element, and wrapper classes that 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 in and parse
Tree = ElementTree (file=xmlfile)
root = Tree.getroot ()
After reading, the tree is the type of ElementTree, obtaining the XML root node using the Getroot () method;
XML sample file:
The code is as follows:
3. Get your son's knot point
Find all child nodes of element:
The code is as follows:
Aarry = Item.findall (' a ')
You can also use GetChildren ():
Childs = Item.getchildren ()
For subitem in Childs:
Print subitem.get (' id ')
4. Insert your son's knot
Method One:
The code is as follows:
Item = Element ("item", {' Sid ': ' 1713 ', ' name ': ' Ityouhui '})
Root.append (item)
Method Two:
The code is as follows:
SE (Root, ' item ', {' sid ': ' 1713 ', ' name ': ' Ityouhui '})
The benefit of Fayi is that you can continue the operation on item after you insert it. Law two is simple in writing, in which SE is subelement, making a statement in the introduction;
5. Operation Properties
Get a property value for element (eg: get the name of item)
The code is as follows:
Print Root.find (' Item/name '). Text
Print item.get (' name ')
Get all attributes of element
The code is as follows:
Print Item.items () # [(' Sid ', ' 1712 '), (' Name ', ' Big cc ')]
Print Item.attrib # {' sid ': ' 1712 ', ' name ': ' Big cc '}
6. Beautify the XML
Before writing, this function is called by incoming root, and the XML file written is nicely formatted:
The code is as follows:
Indent (Root)
Book.write (xmlfile, ' utf-8 ')
The code is 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