Python循环遍历XML

2024-09-28 19:21:41 发布

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

我需要一些迭代的帮助。我在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>全部(古巴哈瓦那市)

我怎么能做到呢?在


Tags: infordatanamesprogramtypeslastprint
2条回答

不是很好的答案,但我建议你试试xmltodict。这个API更容易处理IMO,而且如果您确实遇到了错误,它们肯定不会那么神秘(也就是说,因为完整的结果有效负载只是一个python dict,所以很容易查看并查看哪里可能出了问题)。在

from xml.etree import ElementTree

# I included this list to help
all_nodes = ['sdnEntry', 'uid', 'lastName', 'sdnType', 'programList', 'program', 'akaList',
             'aka', 'uid', 'type', 'category', 'lastName', 'addressList', 'address', 'uid',
             'city', 'country']

required_nodes = ['lastName', 'uid', 'program', 'type', 'category', 'city', 'country']

# required because some names are repeated uid, last
keys = ['sdnEntry_uid', 'lastName', 'program', 'aka_uid', 'type', 'category', 'aka_lastName',
        'address_uid', 'city', 'country']

sdn_data = {}
index = 0

with open('stuff.xml', 'r') as xml_file:
    tree = ElementTree.parse(xml_file)

# iterate all nodes
for node in tree.iter():
    # check if a required node
    if node.tag in required_nodes:
        # add to dictionary
        sdn_data[keys[index]] = node.text
        index += 1

# Use this to test
for key, value in sdn_data.items():
    print(key, value)

输出
索引uid 36
姓氏加勒比航空公司
古巴计划
又名uid 12
a.k.a.
类别强大
aka_lastName航空加勒比公司
地址\u uid 25
哈瓦那市
古巴

相关问题 更多 >