My xml :-
<users>
</users>
i need to just append a child element :-
<users>
<user name="blabla" age="blabla" ><group>blabla</group>
</users>
My code giving some error :(
import xml.etree.ElementTree as ET
doc = ET.parse("users.xml")
root_node = doc.find("users")
child = ET.SubElement(root_node, "user")
child.set("username","srquery")
group = ET.SubElement(child,"group")
group.text = "fresher"
tree = ET.ElementTree(root_node)
tree.write("users.xml")
I missed out "append" , but i don't have idea where to add that. Thanks in advance.
A slightlly modified version to explain what happens:
Change this line
...to this line
The key takeaway here is that
doc
is already a reference to the root node, and is accessed withgetroot()
.doc.find('users')
will not return anything, sinceusers
is not a child of the root, it's the root itself.