Python - 修改xml文件会删除注释

时间:2015-01-29 20:07:15

标签: python xml

让我们说我的xml文件如下所示:

<Products>
  <Product name="first" />

  <!-- some comment -->
  <Product name="second" />

  <Product name="third" />
</Products>

我的剧本:

import xml.etree.ElementTree as ET

tree = ET.parse('test.xml')
root = tree.getroot()

elem = ET.Element('Product')
elem.attrib['name'] = 'fourth'

root.append(elem)

tree.write('test.xml')

生成的xml将如下所示:

<Products>
  <Product name="first" />

  <Product name="second" />

  <Product name="third" />
<Product name="fourth" /></Products>

首先,格式化稍微偏离(空格和新行),但困扰我的是评论行不在新文件中。

有没有办法修改xml文件而不会丢失它们?

0 个答案:

没有答案
相关问题