You should first find an action
element and only then create SubElement
s in it:
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)
prints:
<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>