We can easily Read and write xml in
file using python. In python one library is present name xml, in this library some module is there name as etree, dom, sax,
parsers. By the help of these modules you can read and write xml in file
easily.
We can read and write xml by xml tree or dom
Write xml data in file
import xml
xml_file = open("customer_data.xml", "wb")
xml_file.write('
1
2008
141100
4
2011
59900
68
2011
13600
')
xml_file.close()
Xml parsing or read xml from file
Example: 1File customer_data.xml
<Settings>
<ComputerNameIPs value=""
name=”” />
<ComputerConfig value=""
/>
<ComputerTarget value=""
/>
<ComputerLoginCredentials
value="" >
</Settings>
Python code
import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()
for rank in root.iter(“ComputerNameIPs”):
rank.attrib["value"]=’Ashish’ #this is for writing
rank.attrib["name"]=’computer’
tree.write('country_data.xml')
for rank in root.iter(“ComputerNameIPs”):
data=rank.attrib["value"] #this is for reading
print data
for roots in root:
print root.tag #it will show all tag which is inside
print root.attrib[‘value’] #it will show any attribute in tag
Example-2
File customer_data.xml1 2008 141100 4 2011 59900 Python code 68 2011 13600
for child in root:
print(child.tag, child.attrib)
output...
country {'name': 'Liechtenstein'}
country {'name': 'Singapore'}
country {'name': 'Panama'}
print root[0][1].text
or
for country in root.findall('country'):
if .find('year').text==’2008’:
rank = country.find('year').text
print rank
output…
'2008'
Remove and appending xml data
Python code
for roots in root:
for roo in roots:
if roo.tag =='year':
roots.remove(roo) #this is for removing xml data
tree.write('country_data.xml')
newNode1 = ET.Element('rating')
roots.append(newNode1) #this is for adding data
tree.write('country_data.xml')
Output...
1
</ rating >
141100
4
59900
</ rating >
68
13600
</ rating >
Modifying xml data
for rank in root.iter('rank'):
new_rank = int(rank.text) + 1
rank.text = str(new_rank)
rank.set('updated', 'yes')
tree.write('output.xml')
Output...
2
2008
141100
5
2011
59900
69
2011
13600