追加XML在Python
问题描述:
现有的XML我有一个XML文件:追加XML在Python
<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,然后附加这个第二个XML来代替它。 我没有尝试对第一个块进行注释,但尝试在第一个块中追加第二个xml。我可以附加到它,但我得到'<'和'>'为 & lt;和& gt;分别与
<a>
<b>
<c>
<condition>
....
</condition>
<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>
如何转换这回<
和>
,而不是lt
和gt
?
我该如何删除或注释下面的第一个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
答
您正在添加newxml.xml的路径A/B/C,作为字符串,<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>
个XML更易于操作与设计用于图书馆。 尝试:https://www.crummy.com/software/BeautifulSoup/bs4/doc/ –
tree = etree.parse(open('basexml.xml')#这是我将追加的xml – Bhaskar
@mzjn tree = ET.parse('basexml.xml')#这是我要追加的xml tree1 = etree.parse(open('newxml.xml'))#这是要追加的xml xml_string = etree.tostring (tree1,pretty_print = True) tree.find('a/b/c')。text = xml_string 我将'newxml.xml'转换为字符串'xml_string',然后附加到路径a/b/c第一个xml – Bhaskar