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

标签 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没问题,serie就是一行df。

最佳答案

如果你想要 <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]

关于python - 在python中创建XML文件节点丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53925575/

相关文章:

python - 如何在存在生成器/协程的情况下检查程序状态?

python 2.7程序不向数据库插入数据

c# - 为什么 XmlSerializer 在映射具有相同名称但不同命名空间的类的对象图时无法初始化?

sql - 使用 T-SQL 中另一个(非 XML)列的值更新 XML

php - 我的 Activity 页面没有结果

python - 查找一列中相对于其他列的最大值

python - 如何分组连接行,同时忽略列中的无值?

python - 使用Python进行回溯算法

python - 数据存储 : 中的属性用户已损坏

python - 使用 Python(Pandas 和 Numpy)进行线性回归