python使用elementTree拼接xml(主从健康检查结果合并)

nhc.xml

支持主机显示从机检查结果,且不改变现有接口文件形式
现有结果用*分隔列,用:分隔列名和检测结果
在检测结果里增加从机结果,用/分隔



    Check Result:Pass*Version:11*PatchLevel:3*GDBVersion:7.5
    Check Result:Pass

# coding = utf-8
import xml.etree.ElementTree as ElementTree

local_result_file = './local/nhc.xml'
slave_result_file = './slave/nhc.xml'
local_tree = ElementTree.ElementTree(file=local_result_file)
slave_tree = ElementTree.ElementTree(file=slave_result_file)
local_root = local_tree.getroot()
slave_root = slave_tree.getroot()

# 打印root的标签
# 打印结果
# checkList
print(local_root.tag)

# 打印root的属性
# 打印结果
# {'type': 'omc'}
print(local_root.attrib)

# 打印child的属性
# 打印结果
# systemVersion {'name': 'systemVersion'} Check Result:Pass*Version:11*PatchLevel:3*GDBVersion:7.5
# mysqlStatus {'name': 'mysqlCheck'} Check Result:Pass
for child in local_root:
    print(child.tag, child.attrib, child.text)
print('===========================')


def merge_result(local_str='', slave_str=''):
    local_value_list = local_str.split('*')
    slave_value_list = slave_str.split('*')
    if 'Result:Pass' in local_value_list[0]:
        if 'Result:Pass' not in slave_value_list[0]:
            local_value_list[0] = slave_value_list[0]
    merge_str = local_value_list[0]
    print(merge_str)
    for i in range(1, len(local_value_list)):
        merge_str += '*'
        merge_str += local_value_list[i]
        merge_str += '/'
        merge_str += slave_value_list[i].split(':')[1]
    return merge_str


# 合并各检查结果,使用/分割
for child in local_root:
    node = slave_tree.find(child.tag)
    local_result = child.text
    slave_result = node.text
    child.text = merge_result(local_result, slave_result)

local_tree.write('./nhcNew.xml')

合并后的nhcNew.xml


    Check Result:Pass*Version:11/11*PatchLevel:3/3*GDBVersion:7.5/7.5
    Check Result:Pass

你可能感兴趣的:(python)