Home > database >  I want to replace a text from a subchild in xml with python
I want to replace a text from a subchild in xml with python

Time:11-30

I want to replace the username and the password from the XML and keep the structure like it is. Could u help me pls i tried many things but they didn't work for me.

My Current xml:

<?xml version="1.1" encoding="UTF-8"?>
<Settings>
    <User>
        <Hostname>localhost</Hostname>
        <Databasename>x</Databasename>
        <Username>ABC</Username>
        <Password>124</Password>
        <Remember></Remember>
    </User>
</Settings>

My Code:

mytree = ET.parse('project/config.xml')
myroot = mytree.getroot()

...
username = self.username.text()
password = self.password.text()

if self.rmbCheckBox.checkState() == Qt.Checked:
    for x in myroot.findall('User'):
        #Here i want to change the XML 'Username' and 'Password'
        item = x.find('Username')
mytree.write('user.xml')

CodePudding user response:

Try the below

import xml.etree.ElementTree as ET


xml = '''<?xml version="1.1" encoding="UTF-8"?>
<Settings>
    <User>
        <Hostname>localhost</Hostname>
        <Databasename>x</Databasename>
        <Username>ABC</Username>
        <Password>124</Password>
        <Remember></Remember>
    </User>
</Settings>'''

root = ET.fromstring(xml)
root.find('.//Username').text = 'new_user_name'
root.find('.//Password').text = 'new_password'
ET.dump(root)

output

<Settings>
    <User>
        <Hostname>localhost</Hostname>
        <Databasename>x</Databasename>
        <Username>new_user_name</Username>
        <Password>new_password</Password>
        <Remember />
    </User>
</Settings>
  • Related