import xml.etree.ElementTree as ET
doc = ET.parse("users.xml")
root = doc.getroot() #Returns the root element for this tree.
root.keys() #Returns the elements attribute names as a list. The names are returned in an arbitrary order
for child in root:
username = child.attrib['username']
password = child.attrib['password']
grant_admin_rights = child.attrib['grant_admin_rights']
create_private_share = child.attrib['create_private_share']
uid = child.attrib['uid']
root = ET.Element("users")
user = ET.SubElement(root, "user")
user.set("username",username)
user.set("password",password)
user.set("grant_admin_rights",grant_admin_rights)
user.set("create_private_share",create_private_share)
user.set("uid",uid)
tree = ET.ElementTree(root)
myxml = tree.write("new.xml")
print myxml
my input xml :-
<users>
<user username="admin" fullname="admin" password="admin" create_private_share="yes" remote_access="yes" grant_admin_rights="yes" enable_encrypt_share="yes" volume="DataVolume5" uid="1000"></user>
<user username="os" fullname="sp" password="sp" grant_admin_rights="no" create_private_share="no" uid="1000" ></user>
<user username="us" fullname="sp" password="sp" grant_admin_rights="no" create_private_share="no" uid="1000" ></user>
</users>
Out put of this code :
<user create_private_share="no" grant_admin_rights="no" password="sp" uid="1000" username="us" />
i trying for to get the exact xml as my input xml , but presently it iterating all child but output only coming, the last ? how can i iterate all child and print the exact xml .
in my case print also not working it showing None.
I would like my output should liek this :
<users>
<user username="admin" fullname="admin" password="admin" create_private_share="yes" remote_access="yes" grant_admin_rights="yes" enable_encrypt_share="yes" volume="DataVolume5" uid="1000"></user>
<user username="os" fullname="sp" password="sp" grant_admin_rights="no" create_private_share="no" uid="1000" ></user>
<user username="us" fullname="sp" password="sp" grant_admin_rights="no" create_private_share="no" uid="1000" ></user>
</users>
Thanks in advance 🙂
You have some problems in logic. Only the last value of the loop will be used. You should try to create the nodes every time you go through the loop then join the results and write them to the file