This is my example XML file:
<CATALOG>
<CD>
<DATA key="title">Hide your heart</DATA>
<DATA key="artist">Bonnie Tyler</DATA>
<DATA key="country">UK</DATA>
<DATA key="company">CBS Records</DATA>
<DATA key="price">9.90</DATA>
<DATA key="year">1988</DATA>
<DATA key="times">1</DATA>
</CD>
</CATALOG>
I want to change the value in the the tag data with key "times" and add 1 to it every time I start the script from the terminal.
I tried first of all to read the element with:
import xml.etree.ElementTree
e = xml.etree.ElementTree.parse('test.xml').getroot()
for atype in e.findall('data'):
times=(atype.get('times'))
But i'm already stuck because it doesn't work. If I try to print "times"
I get no output from the terminal.
My Idea was to read it, with a function add to this value 1 and replace it with the total of the sum (2 in this case). And save the modified XML file.
It should be easy to do but I can't figure it out.
EDIT I had to read better the documentation, I tried with:
import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
times = root[0][7].text
newTimes = int(times) + 1
times = newTimes
tree.write('test.xml')
It read correctly the value, add 1 but gives an error if I try to write the file. What am I doing wrong?
EDIT 2
I found the solution, read below my own answer.
DATAelement which has an attributekeywhich has the valuetimes.