Python ElementTree - Append a existing xml with new data
<p>I am new to python/ElementTree .I have the below xml sample:</p>

<pre><code>&lt;users&gt;
  &lt;user username="admin" fullname="admin" password=""  uid="1000"/&gt;
  &lt;user username="user1" fullname="user1" password="" grant_admin_rights="yes"&gt;&lt;group&gt;my_group&lt;/group&gt;&lt;group&gt;group_2&lt;/group&gt;&lt;/user&gt;
&lt;/users&gt;
</code></pre>

<p>I like to append this xml to this existing xml.</p>

<pre><code>&lt;user username= "+usernamne+" password = "+password+"&gt;&lt;group&gt;+newgroup+&lt;/group&gt;&lt;/user&gt;
</code></pre>

<p>So my final out put should be like this :</p>

<pre><code>    &lt;users&gt;
          &lt;user username="admin" fullname="admin" password=""  uid="1000"/&gt;
          &lt;user username="user1" fullname="user1" password="" grant_admin_rights="yes"&gt;&lt;group&gt;my_group&lt;/group&gt;&lt;group&gt;group_2&lt;/group&gt;&lt;/user&gt;
    &lt;user username= "+usernamne+" password = "+password+"&gt;&lt;group&gt;+newgroup+&lt;/group&gt;&lt;/user&gt;
    &lt;/users&gt;

This is my try :-

   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)
</code></pre>
