PythonElementTree basic read operation example can be downloaded from the attachment
1. load xml files
There are two ways to load an XML file: loading a specified string and loading a specified file.
2. obtain the element method
A) through getiterator
B) getchildren
C) find method
D) findall method
Example:
The code is as follows:
#-*-Coding: UTF-8 -*-
From xml. etree import ElementTree
Def print_node (node ):
''''' Print basic node information '''
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 xml file '''
# Loading XML files (two methods: loading a specified string and loading a specified file)
# Root = ElementTree. parse (r "D: \ test. xml ")
Root = ElementTree. fromstring (text)
# Obtain the element method
#1 through getiterator
Lst_node = root. getiterator ("person ")
For node in lst_node:
Print_node (node)
#2 use 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 ())