0

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.

2
  • This is clearly explained in the ElementTree documentation. You're trying to read the attributes of a DATA element. IOW, you're trying to identify the DATA element which has an attribute key which has the value times. Commented Nov 22, 2017 at 16:30
  • You're right, my bad, I had to read better the documentation.. I edited my answer if you would like to help me. Commented Nov 22, 2017 at 16:54

2 Answers 2

0

Very simply:

>>> e.findall('CD')
[<Element 'CD' at 0x7fc0a22c1778>]
>>> e.findall('DATA')
[]

Wrong level of chacking ...

Sign up to request clarification or add additional context in comments.

Comments

0

I found the solution, I only had to first read the value, turn it in an integer, add 1 and replace the value turning it again into a string:

import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()

newTimes = int(root[0][7].text) + 1
root[1][6].text = str(newTimes)

tree.write('test.xml')

That's all.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.