在你提供的代码中,使用ElementTree来处理XML文件时,元素的顺序可能会被打乱。这是因为ElementTree在解析和写入XML文件时,并不保留元素的顺序。如果你需要确保元素的顺序保持不变,可以考虑使用OrderedDict。
下面是一个优化建议,使用collections模块中的OrderedDict来保存接口节点的顺序:
import os
import sys
import getopt,string
import fcntl
import time
import updateVrrpState
import haCommon
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
from cmdtunnel import cmdtunnel_client
from collections import OrderedDict
def update_ospfv2_config_status(interfaces,status):
try:
metric = 0
if status == "master":
metric = 1
else:
metric = 65535
# 读取XML文件
tree = ElementTree.parse('/opt/nsfocus/product/etc/frr/ospf_conf.xml')
root = tree.getroot()
# 使用OrderedDict来保存接口节点的顺序
existing_interfaces = OrderedDict()
# 获取XML中所有interface节点的name属性,组装成字典(按照插入顺序)
for interface in root.findall('.//interface'):
name = interface.get('name')
existing_interfaces[name] = interface
# 遍历传入的接口数组
for intf in interfaces:
if intf in existing_interfaces:
# 如果接口已存在于XML中,则更新metric的值
interface = existing_interfaces[intf]
interface.set('metric', str(metric))
else:
# 如果接口不存在于XML中,则新增一个interface节点
new_interface = ElementTree.Element('interface', attrib={'auth_type': 'none', 'dead_count': '40', 'hello_int': '10', 'key_id': '', 'metric': str(metric), 'name': intf, 'pass': '', 'priority': '1', 'retransmit_int': '5', 'transmit_delay': '1'})
existing_interfaces[intf] = new_interface
# 清空原有的接口节点
root.find('.//interfaces').clear()
# 将按顺序保存的接口节点重新添加到root中
for interface in existing_interfaces.values():
root.find('.//interfaces').append(interface)
# 保存修改后的XML文件
tree.write('/opt/nsfocus/product/etc/frr/ospf_conf.xml', encoding='utf-8', xml_declaration=True)
except Exception as e:
print("An error occurred:", e)
return 10
if __name__ == "__main__":
try:
interfaces = ["G1/1", "G1/2", "G1/7"]
update_ospfv2_config_status(interfaces,"master")
except Exception as e:
print("An error occurred:", e)
sys.exit(1)
通过使用OrderedDict,可以保留字典中元素的插入顺序,从而确保写回XML文件时元素的顺序不会被打乱。
内容由零声教学AI助手提供,问题来源于学员提问