在 python 中将子元素添加到 XML

Adding child element to XML in python

我在 XML 文件中有一个元素为:

<condition>
  <comparison compare="and">
    <operand idref="XXX" type="boolean" />
  </comparison>
</condition>

我需要添加另外两个子元素(child1 和 child2),例如:

<condition>
  <child1 compare='and'>
    <child2 idref='False' type='int' /> 
    <comparison compare="and">
      <operand idref="XXX" type="boolean" />
    </comparison>
  </child1>
</condition>

我继续使用 lxml:

from lxml import etree
tree = etree.parse(xml_file)
condition_elem = tree.find("<path for the condition block in the xml>")
etree.SubElement(condition_elem, 'child1')
tree.write( 'newXML.xml', encoding='utf-8', xml_declaration=True)

这只是将元素 child1 添加为元素条件的子元素,不满足我的要求:

<condition>
  <child1></child1>
  <comparison compare="and">
    <operand idref="XXX" type="boolean" />
  </comparison>
</condition>

有什么想法吗?谢谢

在它的 etree 子模块上使用 lxml 的 objectify 子模块,我会从 root 中删除比较元素,将 child1 元素添加到其中,然后将内容比较返回到其中:

from lxml import objectify

tree = objectify.parse(xml_file)
condition = tree.getroot()
comparison = condition.comparison

M = objectify.ElementMaker(annotate=False)
child1 = M("child1", {'compare': 'and'})
child2 = M("child2", {'idref': 'False', 'type': 'int'})

condition.remove(comparison)
condition.child1 = child1
condition.child2 = child2
condition.child1.comparison = comparison

ElementMaker 是一种易于使用的工具,可用于创建新的 xml 元素。我首先是它的一个实例 (M),它没有注释 xml(用属性乱扔它),然后使用该实例创建您要求的子项。我认为其余部分是不言自明的。