编写XML文件 - 基于变量的多标签

时间:2012-11-08 17:56:40

标签: python xml

我在Python中使用minidom(以及其他)从目录中提取文件列表,获取修改时间,其他misc。数据然后将该数据写入XML文件。数据打印得很好,但是当我尝试将数据写入文件时,我只获取目录中其中一个文件的XML。这是我的代码(为了便于阅读/空间,我删除了大量createElementappendChild方法以及任何不相关的变量:

for filename in os.listdir((os.path.join('\\\\10.10.10.80\Jobs\success'))):

    doc = Document()
    modTime = datetime.datetime.fromtimestamp(os.path.getmtime('\\\\10.10.10.80\Jobs\success\\'+filename)).strftime('%I:%M:%S %p')
    done = doc.createElement('Printed Orders')
    doc.appendChild(done)
    ordernum = doc.createElement(filename)
    done.appendChild(ordernum)
    #This is where other child elements have been removed

    print doc.toprettyxml(indent='  ')
    xmlData = open(day_path, 'w')
    xmlData.write(doc.toprettyxml(indent='  '))

希望这足以看出发生了什么。由于print返回我期望的值,我认为写函数是我出错的地方。

1 个答案:

答案 0 :(得分:2)

如果我理解你的迭代

您不能为每个文件创建一个不同的文档,因此您必须将文档的创建和xml文件的编写放在循环之外

from xml.dom.minidom import Document 
import os,datetime
path = "/tmp/"
day_path ="today.xml"
doc = Document()
done = doc.createElement('Printed Orders')

for filename in os.listdir((os.path.join(path))):

    print "here"
    modTime = datetime.datetime.fromtimestamp(os.path.getmtime(path+filename)).strftime('%I:%M:%S %p')
    doc.appendChild(done)
    ordernum = doc.createElement(filename)
    done.appendChild(ordernum)
    #This is where other child elements have been removed

print doc.toprettyxml(indent='  ')
xmlData = open(day_path, 'w')
xmlData.write(doc.toprettyxml(indent='  '))

修改: 对于HierarchyRequestErr错误,您必须将根元素的创建放在循环之外