Xml在追加时写了两次

时间:2017-12-04 08:05:28

标签: python xml python-2.7 aiml

尝试使用 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>

1 个答案:

答案 0 :(得分:1)

你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)