The 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:
CopyCode 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 ())