使用Python从xml中的一个节点遍历到另一个节点

2024-09-29 21:28:42 发布

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

我对Python中的XML非常陌生,我从网络设备得到以下XML字符串作为响应:

'<Response MajorVersion="1" MinorVersion="0"><Get><Configuration><OSPF MajorVersion="19" MinorVersion="2"><ProcessTable><Process><Naming><ProcessName>1</ProcessName></Naming><DefaultVRF><AreaTable><Area><Naming><AreaID>0</AreaID></Naming><Running>true</Running><NameScopeTable><NameScope><Naming><InterfaceName>Loopback0</InterfaceName></Naming><Running>true</Running><Cost>1000</Cost></NameScope><NameScope><Naming><InterfaceName>Loopback1</InterfaceName></Naming><Running>true</Running><Cost>1</Cost></NameScope><NameScope><Naming><InterfaceName>GigabitEthernet0/0/0/0</InterfaceName></Naming><Running>true</Running><Cost>1</Cost></NameScope></NameScopeTable></Area></AreaTable></DefaultVRF><Start>true</Start></Process></ProcessTable></OSPF></Configuration></Get><ResultSummary ErrorCount="0" /></Response>'

我有以下代码来检索接口信息以及与之相关的接口成本。但是,我也希望将与每个接口关联的“AreaID”标记作为字典的一部分。无法正确导航树以检索AreaID标记值:

for node in x.iter('NameScope'):
int_name = str(node.find('Naming/InterfaceName').text)
d[int_name] = {}
d[int_name]['cost'] = str(node.find('Cost').text)

打印“d”时,此代码提供以下输出:

{'GigabitEthernet0/0/0/0': {'cost': '1'},
 'Loopback0': {'cost': '1000'},
 'Loopback1': {'cost': '1'}}

我希望输出中有类似的内容:

{'GigabitEthernet0/0/0/0': {'cost': '1', 'area': 0},
 'Loopback0': {'cost': '1000', 'area': 0},
 'Loopback1': {'cost': '1', 'area': 0}}

对我的代码的任何建议或修改都将不胜感激


Tags: 代码namenodetruerunningintcostnaming
1条回答
网友
1楼 · 发布于 2024-09-29 21:28:42

我将使用^{}符号:

node.xpath(".//preceding::AreaID")[0].text

我正在执行的完整代码:

from lxml import etree as ET

x = ET.parse("input.xml")
d = {}
for node in x.iter('NameScope'):
    int_name = str(node.find('Naming/InterfaceName').text)
    d[int_name] = {
        'cost': str(node.find('Cost').text),
        'area': node.xpath(".//preceding::AreaID")[0].text 
    }

print(d)

印刷品:

{
    'Loopback0': {'cost': '1000', 'area': '0'}, 
    'Loopback1': {'cost': '1', 'area': '0'}, 
    'GigabitEthernet0/0/0/0': {'cost': '1', 'area': '0'}
}

相关问题 更多 >

    热门问题