How to insert a child subelement in Python Element

2020-07-23 06:48发布

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.

标签: python
2条回答
乱世女痞
2楼-- · 2020-07-23 07:16

A slightlly modified version to explain what happens:

root = ET.fromstring('<users></users>') # same as your doc=ET.parse(...).find(...), btw. doc=root
el = ET.Element('group')   # creating a new element/xml-node
root.append(el)            # and adding it to the root

ET.tostring(root)
>>> '<users><group /></users>'
el.text = "fresher"        # adding your text
ET.tostring(root)
>>>  '<users><group>fresher</group></users>'
查看更多
Juvenile、少年°
3楼-- · 2020-07-23 07:27

Change this line

root_node = doc.find("users")

...to this line

root_node = doc.getroot()

The key takeaway here is that doc is already a reference to the root node, and is accessed with getroot(). doc.find('users') will not return anything, since users is not a child of the root, it's the root itself.

查看更多
登录 后发表回答