python - 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>
”错误消息。
解决方案
经进一步调查,失踪者是来自“猫”。想知道为什么猫会删除它吗?我做了一棵树。转储,就在那里。
推荐阅读
- python - 如何只取整数项并从列表中计算总和?
- java - 如何在 try-catch 块中重新连接到数据库?
- soap - 如何使用脚本视图构建肥皂请求?
- vba - MS Access - 根据使用宏的预定义条件选择特定的行数
- influxdb - 删除属于特定保留策略的度量
- css - CSS如何在悬停在元素上时影响 ::after 状态
- powershell - 在编写 .msi 自定义设置脚本时遇到问题
- javascript - Uncaught (in promise) SyntaxError: Unexpected end of input in React when fetch the API
- sql - 如何在所有表中查找特定列并在 PostgreSQL 中修改该列的值
- ruby-on-rails - 升级铁轨,输出混乱