python - 在python中向XML添加子元素

标签 python xml lxml elementtree xml.etree

我在 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 元素。我首先创建一个不注释 xml 的实例 (M)(用属性散布它),然后使用该实例创建您要求的子项。我认为其余部分是相当不言自明的。

关于python - 在python中向XML添加子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47304314/

相关文章:

xml - 为特定标签替换 XML 文件中的值

php - 使用 simplexml_load_string() 将 XML 转换为 JSON 时如何删除 "@attributes"

python - 使用 Python Iterparse 处理大型 XML 文件

python - 浏览器附加组件生成的合法 Xpath 查询不适用于 urllib2 获取的页面

python - 将某些功能拆分为函数、模块和包的推荐方法?

java - XMLStreamReader - 文件末尾会发生什么?

python - 如何查找 ImageDataGenerator 生成的图像数量

python - lxml etree.parse.xpath() 返回仅包含制表符和换行符的项目

python - 一些数据的Scipy拟合多项式模型

python - 如何找到第一个非零元素和最后一个非零元素并修剪它