【发布时间】:2018-04-28 11:53:29
【问题描述】:
我在 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>
有什么想法吗?谢谢
【问题讨论】:
标签: python xml lxml elementtree xml.etree