Python ElementTree basic read operation example

  • 2020-04-02 09:23:06
  • OfStack

Examples can be downloaded in the attachment
1. Load the XML file
There are two ways to load an XML file, one is to load the specified string, and the other is to load the specified file
2. Method to get element
A) by getiterator
B) the getchildren
C) find methods
D) the.findall method
Here's an example:

#-*- 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 ''' 
#  loading XML File ( 2 methods , Load the specified string, and load the specified file.  
# root = ElementTree.parse(r"D:test.xml") 
root = ElementTree.fromstring(text) 

#  To obtain element The method of  
# 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 methods  
node_find = root.find('person') 
print_node(node_find) 

#4. findall methods  
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())

Related articles: