首页 > 解决方案 > Python elementtree在为非根节点插入子元素时从循环中获取重复元素

问题描述

使用 Python elementtree 尝试使用循环将子元素插入子节点,但会丢失根端节点。

我有以下参数 filename=/Desktop/test.xml 的 XML 并传入“a,b,c”的参数

<root><A></A></root>

代码:

#!/usr/bin/env python

import argparse
from xml.etree import ElementTree as ET

def get_args():
    """ Parse and return the arguments of the application """
    parser = argparse.ArgumentParser(description = "Replace ")
    parser.add_argument('filename',
        action = 'store',
        help = '')
    parser.add_argument('s',
        action = 'store',
        help = '')
    return parser.parse_args()


def appendSS(p, ss):
    for s in ss.split(','):
        w = ET.Element("W")
        w.set("name",s)
        p.append(w)


if __name__ == '__main__':
    """ The starting point of the application """
    args = get_args()
    doc = ET.parse(args.filename)
    root = doc.getroot()

    appendSS(root.find("A"), args.s)
    tree = ET.ElementTree(root)
    if tree.write(args.filename):
        print ("%s was updated successfully!" % args.filename)
    else:
        print ("failed to update %s" % args.filename)

预期的:

<root><A><W name="a"/><W name="b"/><W name="c"/></A></root>

实际的:

<root><A><W name="a"/><W name="b"/><W name="c"/></A>

还收到“更新失败<filename>”错误消息。

标签: pythonxmlelementtree

解决方案


经进一步调查,失踪者是来自“猫”。想知道为什么猫会删除它吗?我做了一棵树。转储,就在那里。


推荐阅读