我正在尝试将xml文件转换为csv文件。如何读取和解析xml文件并将其转换为csv?是否有任何软件包可以将xml转换为csv。
<services>
<service>
<ServiceID>1</ServiceID>
<ServiceName>eVoting Booth</ServiceName>
</service>
<service>
<ServiceID>2</ServiceID>
<ServiceName>Justice of the Peace</ServiceName>
</service>
<service>
<ServiceID>3</ServiceID>
<ServiceName>Library</ServiceName>
</service>
<service>
<ServiceID>4</ServiceID>
<ServiceName>Customer Service</ServiceName>
</service>
<service>
<ServiceID>5</ServiceID>
<ServiceName>Migrant Service</ServiceName>
</service>
</services>
我想要结果
ServiceID | ServiceName
1 | Library
2 | Justice of the Peace
答案 0 :(得分:0)
类似的东西可能起作用:
from lxml import etree
import pandas as pd
tree = etree.parse("input.xml")
df = pd.DataFrame({
"ServiceID" : tree.xpath('/services/service/ServiceID/text()'),
"ServiceName" : tree.xpath('/services/service/ServiceName/text()')
})
df.to_csv("output.csv", sep="|", index = None)
这产生
ServiceID|ServiceName
1|eVoting Booth
2|Justice of the Peace
3|Library
4|Customer Service
5|Migrant Service