Tristan Tran
Tristan Tran

Reputation: 1513

Insert node to ElementTree tree at specific level by name

If I have an XML ElementTree with unknown depth, I want to insert a node as a child node to a specific parent (known). The code I have so far (from some other threads) is as following:

my_tree.xml

<?xml version="1.0" encoding="UTF-8"?>
<data>
  <country name="Singapore">
    <continent>Asia</continent>
    <holidays>      
    </holidays>
    <rank updated="yes">5</rank>
    <year>2011</year>
    <gdppc>59900</gdppc>
    <neighbor name="Malaysia" direction="N"/>
  </country>
</data>
import xml.etree.ElementTree as ET

xml_file = "my_tree.xml"

tree = ET.parse(xml_file)
root = tree.getroot()


newNode = ET.Element('christmas')
newNode.text = 'Yes'


root.insert(0, newNode)

Above, it inserts directly under root. If I want to insert it below a node named <holidays> (not knowing its depth level in the real data), how do I point root to this level? Thanks.

Upvotes: 1

Views: 1381

Answers (2)

balderman
balderman

Reputation: 23815

see below

import xml.etree.ElementTree as ET

xml = '''<?xml version="1.0" encoding="UTF-8"?>
<data>
  <country name="Singapore">
    <continent>Asia</continent>
    <holidays>      
    </holidays>
    <rank updated="yes">5</rank>
    <year>2011</year>
    <gdppc>59900</gdppc>
    <neighbor name="Malaysia" direction="N"/>
  </country>
</data>'''

root = ET.fromstring(xml)
holidays = root.find('.//holidays')
newNode = ET.Element('christmas')
newNode.text = 'Yes'
holidays.append(newNode)
ET.dump(root)

Upvotes: 1

Jack Fleeting
Jack Fleeting

Reputation: 24930

You're almost there; just replace your last line with

target = root.find('.//holidays')    
target.insert(0, newNode)

and see if it works.

Upvotes: 1

Related Questions