026xml module,
Just get to know **
Create a file
Includes tags and tag attributes
# The xml format is as follows:
<?xml version="1.0"?><data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year>2011</year> <gdppc>59900</gdppc> <neighbor name="Malaysia" direction="N"/> </country> <country name="Panama"> <rank updated="yes">69</rank> <year>2011</year> <gdppc>13600</gdppc> <neighbor name="Costa Rica" direction="W"/> <neighbor name="Colombia" direction="E"/> </country></data>
View Code
# Xml operations in python:
1 import xml. etree. elementTree as ET 2 3 tree = ET. parse ("xmltest. xml ") 4 root = tree. getroot () 5 print (root. tag) # Name of the outermost tag 6 7 # traverse xml Document 8 for child in root: 9 print (child. tag, child. attrib) # tag is the tag, and attrib is the attribute 10 for I in child: 11 print (I. tag, I. text) 12 13 # Only traverse the year node 14 for node in root. iter ('Year'): 15 print (node. tag, node. text) 16 # --------------------------------------- 17 import xml. etree. elementTree as ET18 19 tree = ET. parse ("xmltest. xml ") 20 root = tree. getroot () 21 22 # modify 23 for node in root. iter ('Year'): 24 new_year = int (node. text) + 125 node. text = str (new_year) 26 node. set ("updated", "yes") 27 28 tree. write ("xmltest. xml ") 29 30 31 # Delete node32 for country in root. findall ('country'): 33 rank = int (country. find ('rank '). text) 34 if rank> 50: 35 root. remove (country) 36 37 tree. write ('output. xml ')
View Code