繁体   English   中英

使用 python 创建一个 xml 文件

[英]create an xml file using python

我正在开发一个需要生成 xml 文件的项目。 我编写了一个代码来执行 xml,但我的 output 遇到了问题。 我正在尝试遍历 csv 文件并将其转换为 xml

我的代码

import pandas as pd
from itertools import zip_longest
from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import Element, SubElement, tostring
import xml.etree.ElementTree as etree
import os
df= pd.read_csv('detector.csv')
df.head()

df1= df['id'].astype(str)
df2=df['lane'].astype(str)
df3=df['pos'].astype(str)
df4=df['freq'].astype(str)
df5=df['file'].astype(str)

df_all= list(zip_longest(df1, df2, df3, df4, df5))

for i, j, k, l, m in df_all:
    root=Element('additional')
    tree=ElementTree(root)
    child= SubElement(root, 'e1Detector')
    child.set('id', i)
    child.set('lane', j)
    child.set('pos', k)
    child.set('freq', l)
    child.set('file', m)
   
    print(etree.tostring(root))
    tree.write('detector.add.xml')

我得到的只是我的 csv 文件的最后一行。

<additional>
<e1Detector id="e1Detector_77317_2_5" lane="77317_2" pos="1.51" freq="900.0" file="e1Detector_77317_2_5.xml" />
</additional>

我想要的是这个

<additional>
<e1Detector id="e1Detector_77305_1_1" lane="77305_1" pos="11.11" freq="900.0" file="e1Detector_77305_1_1.xml" />
<e1Detector id="e1Detector_77305_2_2" lane="77305_2" pos="11.11" freq="900.0" file="e1Detector_77305_2_2.xml" />
<e1Detector id="e1Detector_77317_0_3" lane="77317_0" pos="2.99" freq="900.0" file="e1Detector_77317_0_3.xml" />
<e1Detector id="e1Detector_77317_1_4" lane="77317_1" pos="2.06" freq="900.0" file="e1Detector_77317_1_4.xml" />
<e1Detector id="e1Detector_77317_2_5" lane="77317_2" pos="1.51" freq="900.0" file="e1Detector_77317_2_5.xml" />
</additional>

我尝试使用 append 但它没有用

你可以在这里找到我的 csv 文件

您需要将树和根元素移出循环,以及写入文件:

root=Element('additional')
tree=ElementTree(root)

for i, j, k, l, m in df_all:
    child= SubElement(root, 'e1Detector')
    child.set('id', i)
    child.set('lane', j)
    child.set('pos', k)
    child.set('freq', l)
    child.set('file', m)

print(etree.tostring(root))
tree.write('detector.add.xml')

否则,您只需在每次运行循环时覆盖文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM