lxml,向SubElemen添加子元素

2024-03-28 08:51:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个如下所示的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(我想添加的新操作的列表):

^{pr2}$

该函数用于在名为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:参数''u parent'的类型不正确(应为lxml.etree.\u元素,获取列表)

有什么办法改变这个功能吗?在


Tags: noversionorderactionxmlflowutfencoding
1条回答
网友
1楼 · 发布于 2024-03-28 08:51:53

您应该首先找到一个action元素,然后在其中创建SubElements:

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)

印刷品:

^{pr2}$

相关问题 更多 >