How to add new data to existing XML using Python ElementTree?

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 add the following to existing XML:

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

so my final conclusion 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) 
+4
source share
2 answers

In ElementTree, Element objects have an append method. Using this method, you can directly add a new XML tag.

For instance:

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

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

+11
source

After receiving the XML root, convert the children of this root into a string - "ET.toString ()" and ".split ()" into parts so that you can create a list and add a new line to this list. And then use ".join ()" to create a line from the list. After that, use the "ET.fromString ()" method to create a new xml. And write it to a file.

-4
source

All Articles