gpt4 book ai didi

python - 如何使用 python 从 XML 文件中解析并仅获取所需的 XML 元素?

转载 作者:行者123 更新时间:2023-12-01 01:40:41 25 4
gpt4 key购买 nike

我有一个如下所示的 XML 文件:

<rpc-reply xmlns:junos="http://xml.juniper.net/junos/15.1R5/junos">
<vlan-information xmlns="http://xml.juniper.net/junos/15.1R5/junos-esw" junos:style="brief">
<vlan-terse/>
<vlan>
<vlan-instance>0</vlan-instance>
<vlan-name>ACRS-Dev2</vlan-name>
<vlan-create-time>Fri Jan 1 00:37:59 2010
</vlan-create-time>
<vlan-status>Enabled</vlan-status>
<vlan-owner>static</vlan-owner>
<vlan-tag>0</vlan-tag>
<vlan-index>2</vlan-index>
<vlan-l3-interface>vlan.15 (UP)</vlan-l3-interface>
<vlan-l3-interface-address>10.8.25.1/24</vlan-l3-interface-address>
<vlan-protocol-port>Port Mode</vlan-protocol-port>
<vlan-members-count>7</vlan-members-count>
<vlan-members-upcount>6</vlan-members-upcount>
</vlan>
<vlan>
<vlan-instance>0</vlan-instance>
<vlan-name>default</vlan-name>
<vlan-create-time>Fri Jan 1 00:37:59 2010
</vlan-create-time>
<vlan-status>Enabled</vlan-status>
<vlan-owner>static</vlan-owner>
<vlan-tag>0</vlan-tag>
<vlan-index>3</vlan-index>
<vlan-l3-interface>vlan.11 (UP)</vlan-l3-interface>
<vlan-l3-interface-address>10.8.27.1/24</vlan-l3-interface-address>
<vlan-protocol-port>Port Mode</vlan-protocol-port>
<vlan-members-count>12</vlan-members-count>
<vlan-members-upcount>2</vlan-members-upcount>
</vlan>
</vlan-information>
</rpc-reply>

由此,我只想要 <vlan-name><vlan-l3-interface-address>将被解析并保存在类似 dict/json 的变量中的标签,其格式为:

{'Vlan-Name' : vlan_name, 'Interface-Address' : interface_addr}

然后为 dicts/json 列表中的每个元素添加这些 dict/json。这是我在列表中解析和插入 json 的代码:

root = tree.getroot()
nw_pool = []
nw_json = {}
for child in root:
for items in child:
for item1 in items:
if 'vlan-l3-interface-address' in item1.tag:
interface_addr = item1.text
nw_json['Interface-Address'] = interface_addr
elif 'vlan-name' in item1.tag:
vlan_name = item1.text
nw_json['Vlan-Name'] = vlan_name
nw_pool.append(nw_json)
print(nw_pool)

但是当我打印nw_pool时,它给我一个输出,其中重复找到的最后一个元素的 json,而不是为每个元素提供不同的字典。

输出:

[{'Vlan-Name': 'default', 'Interface-Address': '10.8.27.1/24'}, {'Vlan-Name': 'default', 'Interface-Address': '10.8.27.1/24'}]

而我想要的输出是:

[{'Vlan-Name': 'ACRS-Dev2', 'Interface-Address': '10.8.25.1/24'}, {'Vlan-Name': 'default', 'Interface-Address': '10.8.27.1/24'}] 

有人可以帮我解决这个问题吗?提前致谢。

最佳答案

您正在覆盖现有的字典,而每次迭代都需要一个新的字典。因此,您需要将 nw_json = {} 放在另一个地方:

root = tree.getroot()
nw_pool = []
for child in root:
for items in child:
nw_json = {} # Work with new dict
for item1 in items:
if 'vlan-l3-interface-address' in item1.tag:
interface_addr = item1.text
nw_json['Interface-Address'] = interface_addr
elif 'vlan-name' in item1.tag:
vlan_name = item1.text
nw_json['Vlan-Name'] = vlan_name
nw_pool.append(nw_json)
print(nw_pool)

关于python - 如何使用 python 从 XML 文件中解析并仅获取所需的 XML 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51929349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com