在python节点中创建XML文件丢失

时间:2018-12-25 20:56:21

标签: python xml pandas elementtree

我想用elementtree库创建一个XML文件。

XML文件应如下所示:

<files>
    <file>
        <ans>EP16</ans>
        <ep></ep>
        <date>2017-03-15</date>
        <concepts>~what</concepts>
    </file>
    <file>
        <ans>EP17</ans>
        <ep>ep6665</ep>
        <date>2017-03-15</date>
        <concepts>~whatever</concepts>
     </file>
     etc
</files>

我尝试通过以下方式进行操作:

import xml.etree.ElementTree as ET
XMLfiles = ET.Element("files")
file= ET.SubElement(XMLfiles, "file")


nrofrows=dffiles.shape[0]
for i in range(nrofrows):
    serie=dffiles.iloc[i]
    child1=ET.SubElement(file, "an")
    child1.text=serie[0]
    child2=ET.SubElement(file, "ep")
    child2.text=serie[1]
    child3=ET.SubElement(file, "date")
    child3.text=serie[2]
    child4=ET.SubElement(file, "concepts")
    child4.text=serie[3]

保存文件:

tree2 = ET.ElementTree(XMLfiles)
filetosave=os.path.join('00DATA_output','bb.xml')
tree2.write(filetosave)

已创建XML文件,但跳过每个文件的关闭。创建的xml文件开始为:

<files>
    <file>
        <ans>EP16</ans>
        <ep></ep>
        <date>2017-03-15</date>
        <concepts>~what</concepts>
   ... ***** closing and open <file> is missing
        <ans>EP17</ans>
        <ep>ep6665</ep>
        <date>2017-03-15</date>
        <concepts>~whatever</concepts>
    </file>
</files>

每次打开和关闭文件的代码缺少什么? 注意:假设要解析的df没问题,那么该系列是df的一行。

1 个答案:

答案 0 :(得分:2)

如果您想在<file>的每一行中使用dffiles标签,也可以在循环中将其移动。

nrofrows = dffiles.shape[0]
for i in range(nrofrows):
    file = ET.SubElement(XMLfiles, "file")
    serie = dffiles.iloc[i]
    child1 = ET.SubElement(file, "an")
    child1.text = serie[0]
    child2 = ET.SubElement(file, "ep")
    child2.text = serie[1]
    child3 = ET.SubElement(file, "date")
    child3.text = serie[2]
    child4 = ET.SubElement(file, "concepts")
    child4.text = serie[3]
相关问题