4

I am new to Python/ElementTree. I have the following XML sample:

<users>
    <user username="admin" fullname="admin" password=""  uid="1000"/>
    <user username="user1" fullname="user1" password="" grant_admin_rights="yes"><group>my_group</group><group>group_2</group></user>
</users>

I would like to append the following to this existing XML:

<user username="+username+" password="+password+"><group>+newgroup+</group></user>

so my final output should be like this:

    <users>
        <user username="admin" fullname="admin" password=""  uid="1000"/>
        <user username="user1" fullname="user1" password="" grant_admin_rights="yes"><group>my_group</group><group>group_2</group></user>
        <user username="+username+" password="+password+"><group>+newgroup+</group></user>
    </users>

This is my attempt:

import sys
import xml.etree.ElementTree as ET

class Users(object):
    def __init__(self, users=None):
        self.doc = ET.parse("users.xml")
        self.root = self.doc.getroot()

    def final_xml(self):
        root_new  = ET.Element("users") 
        for child in self.root:
            username             = child.attrib['username']
            password             = child.attrib['password']  
            user    = ET.SubElement(root_new, "user") 
            user.set("username",username)               
            user.set("password",password) 
            try:
                fullname             = child.attrib['fullname']
            except KeyError:
                pass
            for g in child.findall("group"):
                group     = ET.SubElement(user,"group")
                group.text = g.text
        tree = ET.ElementTree(root_new)
        tree.write(sys.stdout)
1
  • So where does this code try to add the new <user>? Doesn't look to me like you've tried to do what you're asking about. Commented Dec 1, 2012 at 8:38

1 Answer 1

13

In ElementTree, Element objects have an "append" method. By using this method you can directly add the new XML tag.

For example:

user = Element('user')
user.append((Element.fromstring('<user username="admin" fullname="admin" password="xx"  uid="1000"/>')))

where "Element" comes from from xml.etree.ElementTree import Element.

Sign up to request clarification or add additional context in comments.

Comments

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.