所以我是使用Python进行xml解析的新手,并且遇到以下问题:
我正在搜索特定标记并将其值存储到列表中,然后将其写入csv文件。
带有文本的值存储得很好,但似乎带有数字的值失败并出现以下错误:
Traceback (most recent call last):
File "C:\Desktop\IDLE - Copy.py", line 19, in <module>
Qty = things.find('PosQuantityAmt', root.nsmap).text
AttributeError: 'NoneType' object has no attribute 'text'
但是,当我只打印完全相同的行时:
print(things.find('PosQuantityAmt', root.nsmap).text)
我得到的价值很好......
8400.0000
15666.0000
75.0000
135697.0000
4528.0000
3224.0000
21352.0000
9734.0000
352000.0000
732.0000
2539.0000
37.7370
21007.6700
60.0000
1100.0000
59877.3300
30000.0000
30000.0000
30000.0000
30000.0000
30000.0000
这是我的代码:
from lxml import etree
import csv
tree = etree.parse('C:/Desktop/ECDS_POS.xml')
root = tree.getroot()
f = open('C:/Desktop/test.csv', 'w')
csvwriter = csv.writer(f)
head = ['Port Code','ISIN','Qty','Cost']
csvwriter.writerow(head)
for things in root.findall('ROW', root.nsmap):
lists = []
portcode = things.find('CustId',root.nsmap).text
Qty = things.find('PosQuantityAmt', root.nsmap).text
ISIN = things.find('PosSecIsin', root.nsmap).text
cost = things.find('PosCostPriceAmt', root.nsmap).text
lists.append(portcode + ";" + Qty + ";" + ISIN + ";" + cost )
csvwriter.writerow(lists)
f.close()
xml文件的片段:
<?xml version="1.0"?>
-<ECDS RowCount="392" ToDate="2017-10-02" FromDate="2017-10-02" Table="POS" ExtractionTime="2017-10-25T17:44:27"
xmlns="https://cnchedwsvcp01/ecds/pos/1">
-<ROW>
<EntityCod>BZH</EntityCod>
<CustId>707144</CustId>
<PortfId>707144-1</PortfId>
<PosId>SC.707144-1.277639-600.590084....</PosId>
<SystemIdCod>SC</SystemIdCod>
<PosHfmCod>550 05</PosHfmCod>
<PosHfmDsc>Equities</PosHfmDsc>
<PosNameTxt>Hochschild Mining PLC Hochschild Mini/RegSh GBP0.25</PosNameTxt>
<PosValuationDat>2017-10-02</PosValuationDat>
<PosPriceAmt>2.2490</PosPriceAmt>
<PosCcyCod>GBP</PosCcyCod>
<PosPriceTypeCod>0</PosPriceTypeCod>
<PosPriceTypeDsc>UNIT PRICE</PosPriceTypeDsc>
<PosEstimAmt>18891.6000</PosEstimAmt>
<PosEstimRefAmt>25062.4000</PosEstimRefAmt>
<PosEstimRefCcyCod>USD</PosEstimRefCcyCod>
<PosRefRateAmt>0.7537</PosRefRateAmt>
<PosQuantityAmt>8400.0000</PosQuantityAmt>
<PosSecId>277639-600</PosSecId>
<PosSecIsin>GB00B1FW5029</PosSecIsin>
<PosValorenId>2776396</PosValorenId>
<PosSubAssetTypeCod>101</PosSubAssetTypeCod>
<PosSubAssetTypeDsc>EQUITIES</PosSubAssetTypeDsc>
<PosPriceDat>2017-10-24</PosPriceDat>
<XrGroupDsc>EQUITIES</XrGroupDsc>
<XrGroupId>2</XrGroupId>
<PosContractSizeAmt>1</PosContractSizeAmt>
<PosCostEstimAmt>22675.9500</PosCostEstimAmt>
<PosCostEstimRefAmt>30386.3800</PosCostEstimRefAmt>
<PosCostPriceAmt>2.6995</PosCostPriceAmt>
<PosCostPriceRefAmt>3.6176</PosCostPriceRefAmt>
<PosCostPriceRefRateAmt>0.7462</PosCostPriceRefRateAmt>
<PosAssetTypeCod>10</PosAssetTypeCod>
<PosAssetTypeDsc>SHARES</PosAssetTypeDsc>
</ROW>