Aleksander
Aleksander

Reputation: 37

How to change text of element in XML file based on values of other elements using ElementTree

I am trying to edit an XML file using Python ElementTree. I need my code to replace the text of all elements with tag "from" to values of the text of the elements with tag "to". Values should be replaced within parent elements.

Sample XML file:

<note>
    <letter>
      <to>Tove</to>
      <from>Jani</from>
    </letter>
    <letter>
      <to>Mitch</to>
      <from>Mcdeer</from>   
    </letter>
</note>

My code:

import os
import xml.etree.ElementTree as et

base_path = os.path.dirname(os.path.realpath(__file__))

xml_file = os.path.join(base_path, 'note.xml')

#print(xml_file)

tree = et.parse(xml_file)

root = tree.getroot()

for d in tree.findall('.//to'):
    for e in tree.findall('.//from'):
        e.text = d.text

tree.write('note1.xml')

Expected result:

<note>
    <letter>
      <to>Tove</to>
      <from>Tove</from>
    </letter>
    <letter>
      <to>Mitch</to>
      <from>Mitch</from>    
    </letter>
</note>

Actual result:

<note>
    <letter>
      <to>Tove</to>
      <from>Mitch</from>
    </letter>
    <letter>
      <to>Mitch</to>
      <from>Mitch</from>    
    </letter>
</note>

Upvotes: 0

Views: 638

Answers (1)

balderman
balderman

Reputation: 23815

Here

import xml.etree.ElementTree as ET

xml = '''<note>
    <letter>
      <to>Tove</to>
      <from>Jani</from>
    </letter>
    <letter>
      <to>Mitch</to>
      <from>Mcdeer</from>   
    </letter>
</note>'''

root = ET.fromstring(xml)
letters = root.findall('.//letter')
for letter in letters:
    letter.find('from').text = letter.find('to').text
ET.dump(root)

output

<note>
    <letter>
      <to>Tove</to>
      <from>Tove</from>
    </letter>
    <letter>
      <to>Mitch</to>
      <from>Mitch</from>   
    </letter>
</note>

Upvotes: 1

Related Questions