简体   繁体   English

python读取xml文件并转换为csv文件

[英]python read xml file and convert into csv file

I am trying to convert xml file into csv file. 我正在尝试将xml文件转换为csv文件。 How to read and parse xml file and convert into csv? 如何读取和解析xml文件并将其转换为csv? Is there any package to convert xml into 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>

I want result as 我想要结果

ServiceID | ServiceName
1         | Library
2         | Justice of the Peace

something like this could work: 这样的事情可能会起作用:

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)

this produces 这产生

ServiceID|ServiceName
1|eVoting Booth
2|Justice of the Peace
3|Library
4|Customer Service
5|Migrant Service

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

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