python elementTreeを使用してxmlを接合する(主に健康診断結果から合成する)

2343 ワード

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