Examples can be downloaded in the attachment
1. Load XML file
There are 2 ways to load an XML file, one is to load the specified string, and the other is to load the specified file
2. Method of acquiring element
A) through Getiterator
b) Over GetChildren
C) Find method
D) FindAll method
Examples are as follows:
Copy Code code as follows:
#-*-Coding:utf-8-*-
From Xml.etree import ElementTree
def print_node (node):
"' Print the basic information of the node '".
Print "=============================================="
Print "node.attrib:%s"% node.attrib
If Node.attrib.has_key ("age") > 0:
Print "node.attrib[' age ']:%s"% node.attrib[' age ']
Print "node.tag:%s"% Node.tag
Print "node.text:%s"% node.text
def read_xml (text):
' Read the XML file '
# Load XML file (2 methods, one is to load the specified string, the other is to load the specified file)
# root = Elementtree.parse (r "D:\test.xml")
Root = elementtree.fromstring (text)
# methods to get the element
# 1 through Getiterator
Lst_node = Root.getiterator ("person")
For node in Lst_node:
Print_node (node)
# 2 through GetChildren
Lst_node_child = Lst_node[0].getchildren () [0]
Print_node (Lst_node_child)
# 3. Find method
Node_find = root.find (' person ')
Print_node (Node_find)
#4. FindAll method
Node_findall = Root.findall ("Person/name") [1]
Print_node (Node_findall)
if __name__ = = ' __main__ ':
# Read_xml (Open ("Test.xml"). Read ())
Write_xml (Open ("Test.xml"). Read ())