Marvin H Marvin H - 1 month ago 5
Python Question

How to address the next iter with python (xml.etree.ElementTree)?

<storage>
<record>
<values>
<points>99999999</points>
<points>Mr</points>
<points>Marvin</points>
<points>Homes</points>
<points>hardware</points>
<points>true</points>
<points>de</points>
<points>6</points>
<points>false</points>
</values>
</record>
</storage>


Hello,

I am trying to change some xml values with python ( xml.etree.ElementTree ).
This is a small part of a xml data.

appelation=re.compile("Mr")
for fname in root.iter('points'):

if appelation.match(str(pTest)):
fname.text="New Mr/Mrs"
## here i am trying to edit the next iter (<points>Marvin</points>)
##fname.next().text="New name" -> doesnt work


Any suggestion how to address the next iter?
The xml files has alot of tags called <"points"> and the values are always diffrent.

Answer

I assume you are using xml.etree.ElementTree since it is part of the standard library. Consider the following snippet:

appelation = re.compile('Mr')
points = root.iter('points')
for node in points:
    if appelation.match(node.text):
        node.text = 'Monsieur'
        node = next(points)
        node.text = 'Francois'
        break

print ElementTree.dump(root)

In this snippet, points is an iterable which we use to get the next points and search. Once we found the node that we are looking for (Mr), we can do something to that node and the next node (by calling next on the said iterable).

The output:

<storage>
    <record>
      <values>
        <points>99999999</points>
        <points>Monsieur</points>
        <points>Francois</points>
        <points>Homes</points>
        <points>hardware</points>
        <points>true</points>
        <points>de</points>
        <points>6</points>
        <points>false</points>
      </values>
    </record>
  </storage>