[英]Don't understand why getting an AttributeError for one XML field but not others
Below is my code to convert xml to csv. 以下是我将xml转换为csv的代码。
empId
, fullName
are converting as expected, but cannot get city of currentAddress
working. empId
, fullName
被转换为预期,但无法获得城市currentAddress
工作。 What I am doing wrong? 我做错了什么?
If I use currentAddress in emp_head.append it does nothing, if I use "city"
, then it errors out with the error message "AttributeError: 'NoneType' object has no attribute 'tag'
. 如果我在emp_head.append中使用currentAddress,则不执行任何操作;如果我使用
"city"
,则它会出错,并显示错误消息"AttributeError: 'NoneType' object has no attribute 'tag'
。
XML: XML:
<?xml version = '1.0' encoding = 'UTF-8'?>
<ns2:exportEmpData xmlns:ns2="http://webservice.example.com/">
<emplist>
<empId>6029</empId>
<fullName>Justin Clark</fullName>
<currentAddress houseNumber="14" street="Lepanto" city="Barcelona"/>
</emplist>
<emplist>
<empId>6078</empId>
<fullName>Jose Domingo</fullName>
<currentAddress houseNumber="48" street="Gran Via" city="Madrid"/>
</emplist>
</ns2:exportEmpData>
My code: 我的代码:
import xml
import csv
import xml.etree.ElementTree as ET
tree = ET.parse('C:/emp/emplist.xml')
root = tree.getroot()
Emp_data = open('C:/emp/emplist.csv', 'wb')
csvwriter = csv.writer(Emp_data)
emp_head = []
count = 0
for member in root.findall('emplist'):
emp_nodes = []
if count == 0:
empId = member.find('empId').tag
emp_head.append(empId)
fullName = member.find('fullName').tag
emp_head.append(fullName)
currentAddress = member.find('currentAddress').tag
emp_head.append(currentAddress)
csvwriter.writerow(emp_head)
count = count + 1
empId = member.find('empId').text
emp_nodes.append(empId)
fullName = member.find('fullName').text
emp_nodes.append(fullName)
currentAddress = member.find('currentAddress').text
emp_nodes.append(currentAddress)
csvwriter.writerow(emp_nodes)
Emp_data.close()
I need to convert 3 fields from the above xml: 我需要从上面的xml转换3个字段:
empId,fullName,city
6029,Justin Clark,Barcelona
6078,Jose Domingo,Madrid
You need to do the following: 您需要执行以下操作:
currentAddress = member.find('currentAddress').attrib.get('city')
Getting the value of text
is incorrect in this context. 在这种情况下,获取
text
的值是不正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.