python xml配置文件注释和取消注释

使用 comment_xml.py 对 spring-task.xml 进行注释和取消注释,及更改 value 节点的触发时间值

spring-task.xml
#!/usr/local/python3
# -*- coding: utf-8 -*-
# @Date: 2018-04-15 09:00:00
# @Author: Canon
# @Link: https://www.python.org
# @Version: 3.6.1

"""
注释 spring-task.xml 文件

# 注释最后一个标签
# comment_node(doc.getElementsByTagName('bean')[-1])

"""

from xml.dom import minidom
import re

# Spring 定时任务文件
xml_file='spring-task.xml'

# 执行的定时任务
task = "schedulerFactoryBean76,schedulerFactoryBean21,schedulerFactoryBean1"

# 定时任务触发时间
task_time = "0 0/1 * * * ? *".strip()

# 属性值
attri_flag = "schedulerFactoryBean"


def comment_last(doc):
    # 注释最后一个标签
    comment = doc.lastChild.previousSibling
    xml_val = comment.toxml()
    print('re-parsed comment:\n')
    print(xml_val)


def comment_node(node):
    """
    注释 xml 代码
    """
    if task_str in node.getAttribute("id"):
        # print(node.toxml())
        comment = node.ownerDocument.createComment(node.toxml())
        node.parentNode.replaceChild(comment, node)
        return comment


def uncomment_node(doc, xml_file):
    """
    取消注释 xml 代码
    """
    new_doc = ""
    for child in doc.childNodes:
        # 判断节点是否注释
        if child.nodeType == child.COMMENT_NODE:
            # 判断节点是否包含标签的注释内容
            if re.findall("<.*>.*</.*>", child.data, flags=re.DOTALL):
                comment_val = re.findall(".*?<", child.data, flags=re.DOTALL)[0].strip().replace("<", "").replace(" ", "").replace("\n", "")
                # 判断注释内容是否包含除了标签外的其他内容
                if comment_val:
                    new_doc += "<!--" + comment_val + "-->"
                    new_doc += re.findall("<.*>.*</.*>", child.data, flags=re.DOTALL)[0]
                else:
                    new_doc += re.findall("<.*>.*</.*>", child.nodeValue, flags=re.DOTALL)[0]
            else:
                new_doc += "<!--" + child.nodeValue + "-->"
        else:
            new_doc += child.toxml()
    tag_top = ('<beans xmlns="http://www.springframework.org/schema/beans" '
                + 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '
                + 'xsi:schemaLocation="http://www.springframework.org/schema/beans        '
                + 'http://www.springframework.org/schema/beans/spring-beans.xsd">')
    new_xml = tag_top + new_doc + "</beans>"
    w_file = open(xml_file, 'w', encoding="utf-8")
    w_file.write(new_xml)


def comment_task(doc, task_list):
    str_val = doc.getElementsByTagName('bean')
    # 时间节点列表
    time_conf = []
    # 时间节点的 id 列表
    id_list = []
    # 设置任务开启的节点列表
    task_conf = []
    # 遍历所有 bean 节点
    for i in range(len(str_val)):
        node = str_val[i]
        node_id = node.getAttribute("id")
        if node_id:
            if attri_flag in node_id:
                task_conf.append(node)
            else:
                time_conf.append(node)

    # 需要执行的定时任务列表
    for task_node in task_conf:
        if task_node.getAttribute("id") not in task_list:
            node_val = task_node.toxml()
            # 注释不执行的定时任务 (注释最后一部分 Start Spring ScheduleFactory 工厂)
            if '--' in node_val:
                # 删除节点中的注释
                re_val = re.subn(r'<!--.*?-->', '', node_val, flags=re.DOTALL)[0]
                comment = task_node.ownerDocument.createComment(re_val)
                doc.parentNode.replaceChild(comment, task_node)
            else:
                comment = task_node.ownerDocument.createComment(node_val)
                task_node.parentNode.replaceChild(comment, task_node)
        else:
            time_id = task_node.getElementsByTagName('ref')[0].getAttribute("bean")
            id_list.append(time_id)

    # 改变定时任务的触发时间
    for time_node in time_conf:
        if time_node.getAttribute("id") in id_list:
            # 执行的任务改变触发时间
            re_val = re.subn('<value>.*?</value>', '<value>{0}</value>'.format(task_time), time_node.toxml(), flags=re.DOTALL)[0]
            # 创建节点,写入文件会带有 "&lt;"、"&gt;"、"&quot;" 字符, 需要替换为正常字符
            comment = time_node.ownerDocument.createTextNode(re_val)
            time_node.parentNode.replaceChild(comment, time_node)
    xml_val = doc.toxml()
    xml_val = re.sub("&lt;", '<', xml_val)
    xml_val = re.sub("&gt;", '>', xml_val)
    xml_val = re.sub("&quot;", '"', xml_val)
    print(xml_val)
    w_file = open(xml_file, 'w', encoding="utf-8")
    w_file.write(xml_val)


if __name__ == '__main__':
    # 取消注释
    doc = minidom.parse(xml_file).documentElement
    uncomment_node(doc, xml_file)
    # 开启定时任务,改变触发时间
    doc = minidom.parse(xml_file).documentElement
    comment_task(doc, task.split(","))
comment_xml.py

猜你喜欢

转载自www.cnblogs.com/jianeng/p/9333340.html