1

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
0

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

It works. Thank you. Can we do the same in bash script?
Can we do the same in bash script? We are finding issues with Python Mac? Thanks.

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.