不明白为什么要为一个XML字段而不是其他字段获取AttributeError

2024-09-27 21:31:39 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我将xml转换为csv的代码empIdfullName正在按预期转换,但无法使城市currentAddress正常工作。我做错了什么

如果我在emp\u head.append中使用currentAddress,它什么也不做,如果我使用"city",那么它会出错并显示错误消息"AttributeError: 'NoneType' object has no attribute 'tag'

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>

我的代码:

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()

我需要转换上述xml中的3个字段:

empId,fullName,city
6029,Justin Clark,Barcelona
6078,Jose Domingo,Madrid

Tags: csvcitytagcountxmlfindheadmember
1条回答
网友
1楼 · 发布于 2024-09-27 21:31:39

您需要执行以下操作:

currentAddress = member.find('currentAddress').attrib.get('city')

在这种情况下,获取text的值是不正确的

相关问题 更多 >

    热门问题