如何使用python将新元素添加到XML节点

时间:2015-08-10 15:46:04

标签: python xml append

我有以下xml文件:

<Envelope xmlns:ns0="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.a.com">
  <Body>
    <Roles><RoleName>SystemOperator</RoleName></Roles><ns1:AddUser>
      <AddUserRequest Version="1">
        <Login>string</Login>
        <FullName>string</FullName>
        <Password>
          <NewPassword>string</NewPassword>
          <PasswordProfile>string</PasswordProfile>
        </Password>
        <Roles>            
        </Roles>
      </AddUserRequest>
    </AddUser>
  </Body>
<Roles /></Envelope>

我需要使用Python

在节点角色下添加新元素RoleName多个条目
<Envelope xmlns:ns0="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.a.com">
  <Body>
    <Roles><RoleName>SystemOperator</RoleName></Roles><ns1:AddUser>
      <AddUserRequest Version="1">
        <Login>string</Login>
        <FullName>string</FullName>
        <Password>
          <NewPassword>string</NewPassword>
          <PasswordProfile>string</PasswordProfile>
        </Password>
        <Roles>
          <RoleName>string</RoleName>
          <RoleName>string</RoleName> 
          <RoleName>string</RoleName>      
        </Roles>
      </AddUserRequest>
    </AddUser>
  </Body>
<Roles /></Envelope>

我的python代码如下,其中RoleName是一个列表元素

import xml.etree.ElementTree as ET
def SSO_Create_Add_User_XML_File(IntegratorID, ActiveLogin, OwnerCode, Login, FullName, NewPassword, PasswordProfile, RoleName):
    tree = ET.parse('..\AddUser.xml') 
    root = tree.getroot()
    for elem in root.iter():
        print elem.tag 
        if elem.tag == "IntegratorID":
            elem.text = IntegratorID
        if elem.tag == "ActiveLogin":
            elem.text = ActiveLogin
        if elem.tag == "OwnerCode":
            elem.text = OwnerCode
        if elem.tag == "Login":
            elem.text = Login
        if elem.tag == "FullName":
            elem.text = FullName
        if elem.tag == "NewPassword":
            elem.text = NewPassword
        if elem.tag == "PasswordProfile":
            elem.text = PasswordProfile
        if elem.tag == "Roles":
            for roles in RoleName:


    tree.write('..\AddUser.xml') 

0 个答案:

没有答案