Python lxml,将子元素添加到子元素
我创建了一个如下所示的XMLPython lxml,将子元素添加到子元素,python,xml,lxml,Python,Xml,Lxml,我创建了一个如下所示的XML <?xml version='1.0' encoding='utf-8' standalone='no'?> <flow xlmns="urn:opendaylight:flow:inventory"> <strict>false</strict> <instructions> <instruction> <apply-action> &l
<?xml version='1.0' encoding='utf-8' standalone='no'?>
<flow xlmns="urn:opendaylight:flow:inventory">
<strict>false</strict>
<instructions>
<instruction>
<apply-action>
<action>
<order>0</order>
<dec-nw-ttl/>
</action>
</apply-action>
</instruction>
</instructions>
该函数旨在将更多子元素添加到名为action的父项下,因此如下所示:
<?xml version='1.0' encoding='utf-8' standalone='no'?>
<flow xlmns="urn:opendaylight:flow:inventory">
<strict>false</strict>
<instructions>
<instruction>
<apply-action>
<action>
<order>0</order>
<dec-nw-ttl/>
<new-action-1/> #Comment: NEW ACTION
<new-action-2/> #Comment: NEW ACTION
</action>
</apply-action>
</instruction>
</instructions>
假的
0
#评论:新行动
#评论:新行动
这不起作用,它抛出错误:TypeError:参数“\u parent”的类型不正确(应为lxml.etree.\u元素,get list)
您知道如何更改函数来执行此操作吗?您应该首先找到一个
操作元素,然后在其中创建子元素s:
from lxml import etree
data = """<?xml version='1.0' encoding='utf-8' standalone='no'?>
<flow xlmns="urn:opendaylight:flow:inventory">
<strict>false</strict>
<instructions>
<instruction>
<apply-action>
<action>
<order>0</order>
<dec-nw-ttl/>
</action>
</apply-action>
</instruction>
</instructions>
</flow>
"""
def add_flow_action(flow, actions):
action = flow.xpath('//action')[0]
for newaction in actions:
etree.SubElement(action, newaction)
return flow
tree = etree.fromstring(data)
result = add_flow_action(tree, ['new-action-1', 'new-action-2'])
print etree.tostring(result)
从lxml导入etree
data=”“”
假的
0
"""
def添加流动作(流,动作):
action=flow.xpath('//action')[0]
对于操作中的新操作:
etree.SubElement(action,newaction)
回流
tree=etree.fromstring(数据)
结果=添加流程动作(树,['new-action-1','new-action-2'])
打印etree.tostring(结果)
印刷品:
<flow xlmns="urn:opendaylight:flow:inventory">
<strict>false</strict>
<instructions>
<instruction>
<apply-action>
<action>
<order>0</order>
<dec-nw-ttl/>
<new-action-1/>
<new-action-2/>
</action>
</apply-action>
</instruction>
</instructions>
</flow>
假的
0
<flow xlmns="urn:opendaylight:flow:inventory">
<strict>false</strict>
<instructions>
<instruction>
<apply-action>
<action>
<order>0</order>
<dec-nw-ttl/>
<new-action-1/>
<new-action-2/>
</action>
</apply-action>
</instruction>
</instructions>
</flow>