How do I append new data to existing XML using Python ElementTree?

孤人 提交于 2020-01-21 05:21:05

问题


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:


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.




回答2:


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



来源:https://stackoverflow.com/questions/13657341/how-do-i-append-new-data-to-existing-xml-using-python-elementtree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!