如何使用python将复杂的xml转换为csv

时间:2018-10-15 02:20:17

标签: python xml-parsing converters

我需要将xml转换为csv。我尝试了xmlutils库,但无法获取预期的字段。实际上,我的xml在xml树中没有通用标签。 xml样本:

<service.className>
    <Id>3001</Id>
    <sId>12.*</sId>
    <qId>1</qId>
    <timeR>123</timeR>
    <pId>1/1/7</pId>
    <sMode/>
    <highipvalue>1</highipvalue>
    <highipvalue2>1</highipvalue2>
    <highipvalue3>1</highipvalue3>
</service.className>
<service.className>
    <Id>3001</Id>
    <sId>12.*</sId>
    <policy>2</policy>
    <timeR>123</timeR>
    <pId>1/1/7</pId>
    <sMode>mode1</sMode>
    <medipvalue>1</medipvalue>
    <medipvalue2>1</medipvalue2>
    <medipvalue3>1</medipvalue3>
</service.className>
<service.className>
    <Id>3001</Id>
    <sId>12.*</sId>
    <policy>3</policy>
    <timeR>123</timeR>
    <pId>1/1/7</pId>
    <sMode>mode2</sMode>
    <lowipvalue>1</lowipvalue>
    <lowipvalue2>1</lowipvalue2>
    <lowipvalue3>1</lowipvalue3>
</service.className>

以此类推。......

预期的csv输出:

Id  sId qid policyid    timeR   pId sMode   highipvalue highipvalue2    highipvalue3    medipvalue  medipvalue2 medipvalue3 lowipvalue  lowipvalue2 lowipvalue3
3001    12.*    1   0   123 1/01/2007   0   1   1   1   0   0   0   0   0   0
3001    12.*    0   2   123 1/01/2007   mode1   0   0   0   1   1   1   0   0   0
3001    12.*    0   3   123 1/01/2007   mode2   0   0   0   0   0   0   1   1   1

但是现在我只能在csv中获取xml的第一个元素树,如下所示

Id  sId qid policyid    timeR   pId sMode   highipvalue highipvalue2    highipvalue3
3001    12.*    1   0   123 1/01/2007       1   1   1
3001    12.*    0   2   123 1/01/2007   mode1   1   1   1
3001    12.*    0   3   123 1/01/2007   mode2   1   1   1

我尝试过的代码:

import xml.etree.ElementTree as et
from xmlutils.xml2csv import xml2csv
out_csv_path=csv path
in_xml_path=xml path
converter = xml2csv(in_xml_path, out_csv_path, encoding="utf-8")
converter.convert(tag="className",buffer_size=1000,quotes=False)

非常感谢任何帮助。

高级谢谢, 玛尼

0 个答案:

没有答案