lxml,向子元素添加子元素

2 投票
1 回答
1846 浏览
提问于 2025-04-18 01:46

我创建了一个看起来像这样的XML。

<?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(就是这个XML),另一个是actions(我想添加的新动作列表):

def add_flow_action(flow, actions):
   for newaction in actions:
      etree.SubElement(action, newaction)
   return flow

这个函数的目的是在名为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>

但是这样做不成功,出现了错误:TypeError: 参数'_parent'类型不正确(期望是lxml.etree._Element,但得到了列表)。

有没有什么办法可以修改这个函数来实现这个功能?

1 个回答

0

你应该先找到一个 action 元素,然后再在里面创建 SubElement

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)

输出结果是:

<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>

撰写回答