1

我有一个名为 sync_list.xml 的 XML 文档,其结构如下:

root = ET.Element("root")
synced = ET.SubElement(root, "synced")
synced.set("name", "Already Synced")
sfile = ET.SubElement(synced, "sfile")
sfile.set("name", "Filename")
sfile.text = "base"

tree = ET.ElementTree(root)
tree.write("sync_list.xml")

所以我最终得到:

<root><synced name="Already Synced"><sfile name="Filename">base</sfile></synced></root>

我是一个目录中的多个文件。sfile每次打开文件时,我想将这些文件名“附加”为新条目。所以我最终会得到这样的结果:

<root><synced name="Already Synced"><sfile name="Filename">base</sfile><sfile name="Filename">File1.blah</sfile><sfile name="Filename">File2.blah</sfile><sfile name="Filename">File3.blah</sfile></synced></root>

我将如何实现这一目标?非常感谢你的帮助。

4

1 回答 1

0

你快到了。你只需要读回文件并找到其中的<synced>元素:

from __future__ import unicode_literals
from xml.etree import cElementTree as etree

tree = etree.parse('sync_list.xml')
synced = tree.find('synced')
for filename in ["file\u00b9", "file2", "file3"]:
    sfile = etree.SubElement(synced, "sfile", name="Filename")
    sfile.text = filename

tree.write('sync_list_appended.xml', encoding='utf-8', xml_declaration=True)
于 2012-11-20T18:53:37.730 回答