pythonxml解析子级和grand-Children属性

2024-09-27 00:11:12 发布

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

在过去的两个星期里,我一直断断续续地尝试这种方法,并查看python的XML解析文档。我仍然可以判断它是否是Xpath的东西。如果有人能提供一些帮助,我将不胜感激。在

我的XML文件有许多子文件,我正在使用根.findall()要获取myAccessPoints的属性,然后在它下面的三个子级中,我有一个元素,其中包含我要提取的几个属性。但是,到目前为止,我只能用2个for循环来完成这个任务。在

import xml.etree.ElementTree as ET



def apData():

    tree = ET.parse("project.xml")

    root = tree.getroot()
    for topLevels in root.findall("./myAccessPoints//*[@id]"):
        myApId = topLevels.get('id')
        print("AP:%s" % myApId)
        print()
        #return myApId

    for radio in root.findall("./accessPoints/accessPoint/radio/*"):
        rChannel = radio.get('primaryNumber')
        rMac = radio.get('mac')
        rSsid = radio.get('primaryNumber')
        print(rChannel, rMac, rSsid)
        #return rChannel, rMac, rSsid

以下是XML文件的示例:

^{pr2}$

最后,我将使用access point元素属性,例如-->

接入点id

accessPointMeasurement mac,ssid,primaryNumber

技术波段

技术波段

技术波段

有些accessPoint元素有两组无线电,所以我必须获取accessPointMeasurement属性两次。在

我想我必须创建一个类,在这个类中,我必须在它们内部创建列表或字典。在

我不要求任何人为我做任何事情,除了了解如何在一个for循环中获取每个访问点及其属性(如果可能的话)。在

谢谢你的帮助。在


Tags: 文件id元素forget属性rootxml
1条回答
网友
1楼 · 发布于 2024-09-27 00:11:12

我扩展了XML以包含更多的accessPoints和{},并使用lxml库访问其xpath特性。嵌套循环。在

from lxml import etree

tree = etree.parse('temp.xml')
accessPoints = tree.xpath('.//accessPoint')

for accessPoint in accessPoints:
    print ('accessPoint id:', accessPoint.attrib['id'])
    radios = accessPoint.xpath('radio')
    for radio in radios:
        accessPointMeasurement = radio.xpath('accessPointMeasurement')
        print ('\taccessPointMeasurement: ', accessPointMeasurement[0].attrib)
        technologies = radio.xpath('.//technology')
        for technology in technologies:
            print ('\t\ttechnology: ', technology.attrib)

结果如下:

^{pr2}$

相关问题 更多 >

    热门问题