将xml附加到python中的现有xml

时间:2017-05-25 10:23:19

标签: python xml elementtree

我有一个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。我可以将它附加到它但我得到'&lt;'和'&gt;'如 &amp; lt;和&amp; gt;分别为

<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

1 个答案:

答案 0 :(得分:2)

您正在将newxml.xml作为字符串添加到text元素的<c>属性中。这不起作用。您需要将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>