2012-10-30 48 views
0
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") 

輸出創建新的XML: -使用python這個代碼的

<users><user create_private_share="no" grant_admin_rights="no" password="sp" uid 
="1000" username="us" /></users> 

,但我想讓它像這樣: -

<users> 

<user create_private_share="no" grant_admin_rights="no" password="sp" uid 
="1000" username="us" ><group>hfhfhf</group> </user> 

</users> 

,而不是這個<user />,我試圖<user> <group>fgfg</group> </user>。由於

回答