lxml,将SubElement添加到SubElement

时间:2014-04-07 20:01:12

标签: 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>
        <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

该函数用于在父命名操作下添加更多SubElements,因此它看起来像这样:

<?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:Argument&#39; _parent&#39;具有不正确的类型(预期lxml.etree._Element,获得列表)

有关如何更改功能的任何想法吗?

1 个答案:

答案 0 :(得分: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>