我有一个名为user_data.xml的xml,其中包含:
<?xml version="1.0"?>
<users>
<user name="Rocky" id="1" age="38"/>
<user name="Steve" id="2" age="50"/>
<user name="Melinda" id="3" age="38"/>
</users>
我希望在用户中添加新元素,例如:
<?xml version="1.0"?>
<users>
<user name="Rocky" id="1" age="38"/>
<user name="Steve" id="2" age="50"/>
<user name="Melinda" id="3" age="38"/>
<user name="Yondu" id="4" age="55"/>
</users>
我已尝试使用此python代码执行此操作:
class add_user:
root_new = ET.Element("users")
root_new.append((ET.fromstring('<user name="Yondu" id="4" age="55"/>')))
tree = ET.ElementTree(root_new)
tree.write(sys.stdout)
for c in root_new:
print(root_new)
但它不起作用。
关于我该怎么做的任何想法?
答案 0 :(得分:0)
etree.fromstring()
users
,即按root
方法将新元素附加到append
元素。<强>演示强>:
>>> from lxml import etree
>>> input_data = """<?xml version="1.0"?>
... <users>
... <user name="Rocky" id="1" age="38"/>
... <user name="Steve" id="2" age="50"/>
... <user name="Melinda" id="3" age="38"/>
... </users>"""
>>> root = etree.fromstring(input_data)
>>> new_user = etree.Element("user", {"name":"Yondu", "id":"4", "age": "55"})
>>> root.tag
'users'
>>> root.append(new_user)
>>> print etree.tostring(root, method="xml", pretty_print=True)
<users>
<user name="Rocky" id="1" age="38"/>
<user name="Steve" id="2" age="50"/>
<user name="Melinda" id="3" age="38"/>
<user age="55" name="Yondu" id="4"/></users>
>>>
注意:做必要的异常处理。