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

python read xml file and convert into csv file

我正在尝试将 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

类似这样的方法可行:

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