Python ElementTree子

时间:2015-04-22 21:40:13

标签: python elementtree

是否有办法结束每个设置节点而不是结束?额外/设置/设置/设置结束标签是我想摆脱的东西。我使用set但有些东西告诉我我应该使用append或其他东西添加其他设置名称而不是创建设置的子元素。

The code is generating:(I want to remove the /Setting/Setting/Setting?)
Payload returned = <
update_app_profile odpApiToken="6b" odpCmd="save" odpExt="6629" odpUser="profileApiUser">
<dynamicsettings>
    <Group Name="BASE">
        <Setting Name="CTInt" Value="44">
        <Setting Name="CTTime" Value="11:11:11">
        <Setting Name="CTList" Value="Half-Life 2">
        <Setting Name="Regexp_Base" Value="STR1">
        <Setting Name="CTDate" Value="2016-01-01">
        <Setting Name="CTString" Value="qwe" />
        </Setting></Setting></Setting></Setting></Setting>
     </Group>
  </dynamicsettings>
</update_app_profile>



def create_post_request(self, odpExt, odpCmd, dict):
    '''
    <?xml version="1.0"? encoding="UTF-8">
    <update_app_profile odpCmd="save" odpUser="sgoel" odpPwd="sgoel123" odpExt="8114">
      <dynamicsettings>
        <Group Name="ApplicationParameters">
            <Setting Name="CTTemp1" Value="12"/>
            <Setting Name="CTTemp2" Value="test1"/>
        </Group>
      </dynamicsettings>
    </update_app_profile>
    '''
    dict = {'.//CTDate':'2016-01-01', './/CTString': 'qwe', './/Regexp_Base': 'STR1', './/CTTime': '11:11:11', './/CTInt': '44', './/CTList': 'Half-Life 2'}
    root = ET.Element("update_app_profile")
    root.set("odpCmd", odpCmd)
    root.set("odpExt", odpExt)
    root.set("odpUser", "profileApiUser")
    root.set("odpApiToken", "6b")

    tree= ET.SubElement(root,"dynamicsettings")
    #tree.set("Group Name", "Group1")
    tree = ET.SubElement(tree, "Group")
    tree.set("Name","BASE" )
    #tree = ET.SubElement(tree, "Setting")

    #tree.append("Setting")


    for item, value in dict.iteritems():
        print item + value
        tree = ET.SubElement(tree, "Setting")
        tree.set("Name", item[3:])
        tree.set("Value", value)

    #tree.set("ApplicationParameters")

    return ET.tostring(root)

1 个答案:

答案 0 :(得分:1)

替换:

tree = ET.SubElement(tree, "Setting")
tree.set("Name", item[3:])
tree.set("Value", value)

使用:

setting = ET.SubElement(tree, "Setting")
setting.set("Name", item[3:])
setting.set("Value", value)

然后设置将全部是一个tree的子元素。