在Elementtree中附加文件名

时间:2012-11-20 18:29:17

标签: python elementtree

我有一个名为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>

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

1 个答案:

答案 0 :(得分: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)