我从xml文件中解析了节点值,并想将输出另存为python中的csv,但是在编写csv时出错。
下面是xml的摘要,其中包含我要解析的唱名投票结果的信息,由于我只想从中获取FirstName / LastName / PartyName / VoteValueName / AffiliationId,因此我构建了以下代码
from xml.dom import minidom
doc = minidom.parse("C:/../vote880.xml")
filename = "vote880.csv"
f = open(filename, "w")
headers = "FirstName, LastName, PartyName, VoteValueName, MemberId, AffiliationId\n"
f.write(headers)
VoteParticipants = doc.getElementsByTagName("VoteParticipant")
for VoteParticipant in VoteParticipants:
FirstName = VoteParticipant.getElementsByTagName("FirstName")[0]
LastName = VoteParticipant.getElementsByTagName("LastName")[0]
PartyName = VoteParticipant.getElementsByTagName("PartyName")[0]
VoteValueName = VoteParticipant.getElementsByTagName("VoteValueName")[0]
MemberId = VoteParticipant.getElementsByTagName("MemberId")[0]
AffiliationId = VoteParticipant.getElementsByTagName("AffiliationId")[0]
print("FirstName:%s, LastName:%s, PartyName:%s, VoteValueName:%s, MemberId:%s, AffiliationId:%s" %
(FirstName.firstChild.data, LastName.firstChild.data, PartyName.firstChild.data, VoteValueName.firstChild.data, MemberId.firstChild.data, AffiliationId.firstChild.data))
f.write(FirstName + "," + LastName + "," + PartyName + "," + VoteValueName + "," + MemberId + "," + AffiliationId + "\n")
f.close()
但是,python返回TypeError: unsupported operand type(s) for +: 'Element' and 'str'
。
如果我正确理解,看来我需要在编写csv之前将从xml获得的元素转换为字符串,但是我不知道该怎么做。任何评论将不胜感激。
-<VoteParticipant>
<ParliamentNumber>38</ParliamentNumber>
<SessionNumber>1</SessionNumber>
<DecisionEventDateTime xsi:nil="true"/>
<DecisionDivisionNumber>190</DecisionDivisionNumber>
<PersonShortHonorific>Hon.</PersonShortHonorific>
<ConstituencyName>Kootenay—Columbia</ConstituencyName>
<VoteValueName>Yea</VoteValueName>
<MemberId>1463</MemberId>
<AffiliationId>56252</AffiliationId>
<Name>Mr. Jim Abbott</Name>
<FirstName>Jim</FirstName>
<LastName>Abbott</LastName>
<Province>British Columbia</Province>
<PartyName>Conservative</PartyName>
<Yea>1</Yea>
<Nay>0</Nay>
<Paired>0</Paired>
<SittingNumber>159</SittingNumber>
</VoteParticipant>