Reputation: 45
I have xml file
<?xml version="1.0"?>
<data>
<country name="Panama">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Malaysia">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Liechtenstein">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
I need to find all country tags check the text with the current position of my list of countries if they are not the same we replace the country name by the right name from my list. It should also create a log.txt file (this part is ok). For example, some names are not in order (Panama's neighbors are not Austri and Switzerland) so they need to be replaced and this is a long xml so I want to write a script that will do it automatically.
import xml.etree.ElementTree as ET
import os
from xml.etree.ElementTree import SubElement
base_path = os.path.dirname(os.path.realpath(__file__))
xml_file = os.path.join(base_path, 'data.xml')
tree = ET.parse(xml_file)
root = tree.getroot()
Tags = ['country', 'rank', 'year']
right_data = ['Liechtenstein', 'Singapore', 'Panama']
# I need a log of the changes
f = open('Log.txt','w')
i =0
for tag in Tags[i:]:
print tag
for child in root.iter():
print child
if tag == child.tag:
print 'We found matching tag %s' % tag
if child.text != right_data[i]:
print 'We are changing %s ' % child.text, 'to --> %s'% right_data[i]
f.write('Changing %s -->' % child.text)
f.write('to name %s\n' % right_data[i])
#This is where the problems start
#This is supposed to find text attribute and replace it the right_data[i] at position i
#I get this error when I run my program
#SyntaxError: can't assign to function call
tree.find(child.text) = right_data[i]
else:
"There is no such tag"
f.close()
new_data = ET.tostring(root)
new_xml = open('dataUpdated.xml', 'w')
new_xml.write(new_data)
I know I can replace text on xml file this way.
tree.find('Panama').text = 'Liechtenstein'
tree.write(datafile)
However when I pass a list (righ_data[] and child.text) as arguments it does not like it and it gives me the error described above.
Upvotes: 0
Views: 719
Reputation: 45
I stopped using find() method. See below for how I solved the problem. Key and val are my dictionary.
customDict = {'Soap':'Dial', 'Shampoo': 'H&S'}
for child in root.iter():
for key, val customDict.items():
if child.tag == key:
child.tex = val
This will find the tag, check that it is the right tag and modify it accordingly.
Upvotes: 1