2012-10-30 13 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") 

print myxml 

내 입력 XML을 작동하지 않습니다 : - :는 파이썬에서

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

내가 정확한 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> 

아웃 내 입력 XML,하지만 지금은 모든 자식 iterating하지만 출력에만오고, 마지막? 어떻게 모든 아이를 반복하고 정확한 XML을 인쇄 할 수 있습니다.

제 경우에도 인쇄되지 않습니다. 표시하지 않음.

내 출력이 liek해야 싶습니다 사전에

<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> 

감사합니다 :)

답변

2

당신은 논리에 약간의 문제가있다. 루프의 마지막 값만 사용됩니다. 루프를 거쳐 결과를 결합하고 파일에 쓸 때마다 노드를 만들어야합니다.