python XML to CSV解析结果非

时间:2016-06-26 19:08:35

标签: python xml csv

我有这个xml但有问题解析它到csv,我尝试了简单的print语句,但仍然没有得到任何价值:

<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.008.001.02" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <CstmrDrctDbtInitn>
        <GrpHdr>
            <MsgId>1820</MsgId>
            <CreDtTm>2016-05-17T11:56:12</CreDtTm>
            <NbOfTxs>197</NbOfTxs>
            <CtrlSum>136661.81</CtrlSum>
            <InitgPty>
                <Nm>GS Netherlands CDZ C.V.</Nm>
            </InitgPty>
        </GrpHdr>
    </CstmrDrctDbtInitn>
    <CstmrDrctDbtInitn>
        <GrpHdr>
            <CreDtTm>2016-05-18T10:34:51</CreDtTm>
            <NbOfTxs>1</NbOfTxs>
            <CtrlSum>758.99</CtrlSum>
            <InitgPty>
                <Nm>GS Netherlands CDZ C.V.</Nm>
            </InitgPty></GrpHdr></CstmrDrctDbtInitn>
</Document>

我希望迭代每个节点的值。

到目前为止,我编写的代码如下:

import xml.etree.ElementTree as ET
import csv
with open("D:\Python\Dave\\17_05_16_1820_DD201606B10_Base.xml") as myFile:
    tree = ET.parse(myFile)
ns = {'d': 'urn:iso:std:iso:20022:tech:xsd:pain.008.001.02'}
# open a file for writing
Resident_data = open('Bank.csv', 'w')
# create the csv writer object
csvwriter = csv.writer(Resident_data)
resident_head = []

#write Header
MsgId = 'MsgId'
resident_head.append(MsgId)
CreDtTm = 'CreDtTm'
resident_head.append(CreDtTm)
NbOfTxs = 'NbOfTxs'
resident_head.append(NbOfTxs)
CtrlSum = 'CtrlSum'
resident_head.append(CtrlSum)
csvwriter.writerow(resident_head)

for member in tree.findall('.//d:Document/d:CstmrDrctDbtInitn/d:GrpHdr/d:MsgId', ns):
    resident = []
#write values
    MsgId = member.find('MsgId').text
    resident.append(MsgId)
    CreDtTm = member.find('CreDtTm').text
    resident.append(CreDtTm)
    NbOfTxs = member.find('NbOfTxs').text
    resident.append(NbOfTxs)
    CtrlSum = member.find('CtrlSum').text
    resident.append(CtrlSum)
    csvwriter.writerow(resident)
Resident_data.close()

我没有收到任何错误,我的Bank.csv只有标题但没有数据请帮助

0 个答案:

没有答案