将 xml 附加到 python 中现有的 xml

Append xml to existing xml in python

我有一个 XML 文件:

<a>
    <b>
        <c>
            <condition>
            ....

            </condition>
        </c>
    </b>
</a>

我有另一个 XML 字符串类型为:

<condition>
  <comparison compare="and">
    <operand idref="Agent" type="boolean" />
    <comparison compare="lt">
      <operand idref="Premium" type="float" />
      <operand type="int" value="10000" />
    </comparison>
  </comparison>
</condition>

我需要在第一个 xml 中注释 'condition block',然后附加第二个 xml 来代替它。 我没有尝试评论第一个块,但试图在第一个块中附加第二个 xml 。我可以将它附加到它,但我得到的是“<”和“>” <; >分别为

<a>
    <b>
        <c>
            <condition>
            ....

            </condition>

                &lt;condition&gt;
 &lt;comparison compare="and"&gt;
&lt;operand idref="Agent" type="boolean"/&gt;
&lt;comparison compare="lt"&gt;
  &lt;operand idref="Premium" type="float"/&gt;
  &lt;operand type="int" value="10000"/&gt;
&lt;/comparison&gt;
&lt;/comparison&gt;
&lt;/condition&gt;

如何将其转换回 <> 而不是 ltgt

以及如何删除或评论第一个 xml 的 <condition> 块,我将在其下方附加新的 xml?

tree = ET.parse('basexml.xml')  #This is the xml where i will append
tree1 = etree.parse(open('newxml.xml'))  # This is the xml to append
xml_string = etree.tostring(tree1, pretty_print = True)  #converted the xml to string
tree.find('a/b/c').text = xml_string #updating the content of the path with this new string(xml)

我把'newxml.xml'转换成字符串'xml_string'然后附加到第一个xml

的路径a/b/c

您正在将 newxml.xml 作为字符串添加到 <c> 元素的 text 属性。那是行不通的。您需要添加一个 Element 对象作为 <c>.

的子对象

这是如何完成的:

from xml.etree import ElementTree as ET

# Parse both files into ElementTree objects
base_tree = ET.parse("basexml.xml")
new_tree = ET.parse("newxml.xml")

# Get a reference to the "c" element (the parent of "condition")
c = base_tree.find(".//c")

# Remove old "condition" and append new one
old_condition = c.find("condition")
new_condition = new_tree.getroot()
c.remove(old_condition)
c.append(new_condition)

print ET.tostring(base_tree.getroot())

结果:

<a>
  <b>
    <c>
      <condition>
  <comparison compare="and">
    <operand idref="Agent" type="boolean" />
    <comparison compare="lt">
      <operand idref="Premium" type="float" />
      <operand type="int" value="10000" />
    </comparison>
  </comparison>
</condition></c>
  </b>
</a>