Xml 追加时写了两次

Xml written twice while appending

尝试使用 xml.etree.ElementTree 附加现有 xml 文件时。子元素被写入两次。有什么办法可以克服这个问题吗?

这是我当前的代码:

with open('filename.aiml',"a+") as f:
                        tree=ET.parse(f)
                        root=tree.getroot()
                        rootTag=root.find('.')
                        category=ET.SubElement(rootTag,'category')
                        pattern=ET.SubElement(category,'pattern')
                        pattern.text=input_text.upper()
                        template=ET.SubElement(category,'template')
                        template.text=response
                        root.append(category)
                        tree.write(open("filename.aiml","w+"),encoding='ISO-8859-1')

XML前写:

<?xml version='1.0' encoding='ISO-8859-1'?>
<aiml version="1.0">
<category>
<pattern>WHAT IS DEEP LEARNING</pattern>
<template>Deep learning (also known as deep structured learning or hierarchical learning) is part of a broader family of machine learning methods based on learning data representations, as opposed to task-specific algorithms.</template>
</category>

XML写完后:

  <?xml version='1.0' encoding='ISO-8859-1'?>
    <aiml version="1.0">
    <category>
    <pattern>WHAT IS DEEP LEARNING</pattern>
    <template>Deep learning (also known as deep structured learning or hierarchical learning) is part of a broader family of machine learning methods based on learning data representations, as opposed to task-specific algorithms.</template>
    </category>
 <category>
<pattern>WHAT IS PROOF OF CONCEPT</pattern>
<template>Proof of Concept (PoC) is a realization of a certain method or idea in order to demonstrate its feasibility.</template>
</category>
<category><pattern>TELL ME ABOUT POC</pattern>
<template>Proof of Concept (PoC) is a realization of a certain method or idea in order to demonstrate its feasibility</template>
</category>
<category><pattern>WHAT IS PROOF OF CONCEPT</pattern>
<template>Proof of Concept (PoC) is a realization of a certain method or idea in order to demonstrate its feasibility</template>
</category>
<category><pattern>TELL ME ABOUT POC</pattern>
<template>Proof of Concept (PoC) is a realization of a certain method or idea in order to demonstrate its feasibility.</template></category>

你 xml 在解析时抛出错误,所以我会在这里举个例子。

解析您的数据

root= ET.XML(filename)

随心所欲地进行修改(添加节点、值) 例如来自 python 文档

for rank in root.iter('rank'):
...     new_rank = int(rank.text) + 1
...     rank.text = str(new_rank)
...     rank.set('updated', 'yes')

所有更改都保存到根元素。

将其写入 xml 文件

您需要将 root 传递给 ET.ElementTree(),这将保存您之前的所有更改并写入 xml

with open('d:\output.xml', 'wb') as file:
    ET.ElementTree(root).write(file, encoding='utf-8', xml_declaration=True)