Reputation: 23
I need to modify the online_hostname key value in XML using python. I tried xml element tree but it does not work.
import xml.etree.ElementTree as ET
xml_tree = ET.parse('test.xml')
root = xml_tree.getroot()
root[0][0] = "requiredvalue"
test.xml file is as below:
<?xml version="1.0" encoding="UTF-8" ?>
<bzinfo>
<myidentity online_hostname="testdevice-air_2022_01_25"
bzlogin="[email protected]" />
</bzinfo>
Error:
IndexError: child assignment index out of range
Upvotes: 1
Views: 580
Reputation: 81594
It is much better to explicitly search the required node (find
will do in this case) instead of using indexes on the root
node:
import xml.etree.ElementTree as ET
xml_tree = ET.parse('test.xml')
root = xml_tree.getroot()
myidentity_node = root.find('myidentity')
myidentity_node.attrib['online_hostname'] = 'required_value'
xml_tree.write('modified.xml')
modified.xml after running this code:
<bzinfo>
<myidentity bzlogin="[email protected]" online_hostname="required_value" />
</bzinfo>
Upvotes: 1