Examples can be downloaded in attachments
1. Loading an XML file
There are 2 ways to load an XML file, one to load the specified string, and two to load the specified file
2. How to obtain the element
A) through Getiterator
b) Over GetChildren
C) Find method
D) FindAll method
Examples are as follows:
Copy CodeThe code is as follows:
#-*-Coding:utf-8-*-
From Xml.etree import ElementTree
def print_node (node):
"Print node basic 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 '
# Load the XML file (2 methods, one is to load the specified string, and the second is to load the specified file)
# root = Elementtree.parse (r "D:\test.xml")
Root = elementtree.fromstring (text)
# methods to get Element
# 1 via Getiterator
Lst_node = Root.getiterator ("person")
For node in Lst_node:
Print_node (node)
# 2 via 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 ())