在python中向XML添加子元素

在python中向XML添加子元素,python,xml,lxml,elementtree,xml.etree,Python,Xml,Lxml,Elementtree,Xml.etree,我在XML文件中有一个元素,如下所示: <condition> <comparison compare="and"> <operand idref="XXX" type="boolean" /> </comparison> </condition> 我需要添加两个其他子元素(child1和child2),例如: 我继续使用lxml: from lxml import etree tree = etree.par

我在XML文件中有一个元素,如下所示:

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

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


我继续使用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)
从lxml导入etree
tree=etree.parse(xml_文件)
条件元素=tree.find(“”)
子元素(条件元素'child1')
write('newXML.xml',encoding='utf-8',xml\u declaration=True)
这只是将元素child1添加为元素条件的子元素,如下所示,不满足我的要求:

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


有什么想法吗?感谢使用lxml的objectify子模块而不是etree子模块,我将从根中删除比较元素,将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元素。我首先创建一个不注释xml的实例(M)(用属性填充它),然后使用该实例创建您要求的子对象。我认为,其余的都是不言自明的。

关于标记名的一个词,因为objectify对这些名称有点滑稽。当我创建child1和child2元素时,第一个参数确定标记名,即引用的“child1”/“child2”。为了清楚起见,我只是对python变量使用了相同的名称。但是,当我将这些元素添加到“condition”元素时,它们的标记名将更改为属性的标记名。如果我使用了“condition.evil_spawn=child1”,则condition子级的标记名将是“evil_spawn”,而不是child。因为我们仍然在这里使用“child1”,所以没有任何变化。如果在同一级别中有多个元素,我该怎么办?
comparison=condition。comparison
以标记名为“comparison”的第一个元素为目标。要获取
比较
元素的列表,请执行
条件。比较[:]
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