我需要一些迭代的帮助。我在XML中的根是sdentry。如果我使用[0]而不在doc中进行任何迭代,我可以从中检索文本值,但是当我执行循环时,我会收到诸如“last_names=sdns.getElementsByTagName(“姓氏”)。AttributeError:“NodeList”对象没有属性“getElementsByTagName”'
我的工作代码-没有任何迭代,如下所示:
from xml.dom import minidom
xmldoc = minidom.parse("/Users/cohen/Documents/project/sdn.xml")
sdns = xmldoc.getElementsByTagName("sdnEntry")[0]
last_names = sdns.getElementsByTagName("lastName")[0]
ln = last_names.firstChild.data
types = sdns.getElementsByTagName("sdnType")[0]
t = types.firstChild.data
programs = sdns.getElementsByTagName("programList")[0] #program.firstChild.data
s = programs.getElementsByTagName("program")[0].firstChild.data
akas = sdns.getElementsByTagName("akaList")[0] #child lastName.fourthChild.data
a = akas.getElementsByTagName("aka")[0]
a1 = a.getElementsByTagName("lastName")[0].firstChild.data
addresses = sdns.getElementsByTagName("addressList")[0]
ad1 = addresses.getElementsByTagName("address")[0]
ad2 = ad1.getElementsByTagName("city")[0]
city= ad2.firstChild.data
ad3 = ad1.getElementsByTagName("country")[0]
country = ad3.firstChild.data
这就是我的XML的外观:
^{pr2}$下面是我的for循环。 请告知。提前谢谢你!在
for sdn in sdns:
for ln in last_names:
print(ln)
for t in types:
print(t)
for program in programs:
print (s)
for aka in akas:
print(a1)
for address in addresses:
print(city)
print(country)
我需要将每个sdnEntry
存储在我的数据库中,因此我需要每个条目只知道
<name> (lastName AEROCARIBBEAN AIRLINES)
<sdnType>
(实体)`<programs>
来自程序列表,例如(CUBA计划),但它们可以更多<aka><lastName>
(航空加勒比)所有的<address>
全部(古巴哈瓦那市)我怎么能做到呢?在
不是很好的答案,但我建议你试试xmltodict。这个API更容易处理IMO,而且如果您确实遇到了错误,它们肯定不会那么神秘(也就是说,因为完整的结果有效负载只是一个python dict,所以很容易查看并查看哪里可能出了问题)。在
输出
索引uid 36
姓氏加勒比航空公司
古巴计划
又名uid 12
a.k.a.
类别强大
aka_lastName航空加勒比公司
地址\u uid 25
哈瓦那市
古巴
相关问题 更多 >
编程相关推荐