【问题标题】:Don't understand why getting an AttributeError for one XML field but not others不明白为什么会为一个 XML 字段而不是其他字段获取 AttributeError
【发布时间】:2019-01-17 22:49:27
【问题描述】:

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

如果我在 emp_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

【问题讨论】:

  • 请将完整的错误回溯添加到您的问题中。

标签: python xml csv


【解决方案1】:

您需要执行以下操作:

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

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

【讨论】:

  • 这就像一种享受。谢谢。但是,我遇到了上述 xml 的另一个问题。不是每个员工都会收到“currentAddress”元素。如何使其成为可选?
猜你喜欢
  • 2016-10-03
  • 1970-01-01
  • 2021-11-18
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 2018-04-30
  • 1970-01-01
相关资源
最近更新 更多