Get XML Node Content 获取xml节点内容

import configparser
import os.path
import re
from datetime import datetime
import os.path
import tkinter
from tkinter import *
from tkinter import filedialog
from tkinter.ttk import *
from tkinter.messagebox import *
import numpy as np
import pandas as pd
# table_list = []
ini_path = ''
app_name = ''
excel_path = ''
dsl_path = ''
log_path_list = []
config_path = ''

class ReplaceFileKey:
    def __init__(self, file_name,):
        self.file_name = file_name
        self.file_lines = []
        self.file_names = []
        self.line_record = []

# 遍历目录下所有以key为后缀的文件列表
    def find_file_by_dir(self, directory, key):

        self.file_names.clear()
        if not os.path.exists(directory):
            print(directory + " ,dir not exits")
            return self.file_names
        # 遍历目录及其子目录下所有文件
        for root, dirs, files in os.walk(directory):
            for file in files:
                # 判断文件名是否以"flow"结尾
                if file.endswith(key):
                    # 将符合条件的文件名添加到列表中
                    self.file_names.append(os.path.join(root, file))
        print(self.file_names)
        return self.file_names


    # 遍历目录下所有匹配regexp文件列表
    def find_file_by_regexp(self,directory, key, regexp):

        if regexp == '':
            return self.find_file_by_dir(directory, key)

        self.file_names.clear()
        if not os.path.exists(directory):
            print(directory + " ,dir not exits")
            return self.file_names
        pattern_re = re.compile(regexp)
        # 遍历目录及其子目录下所有文件
        for root, dirs, files in os.walk(directory):
            for file in files:
                # 判断文件名是否以"flow"结尾
                matches = pattern_re.search(file)
                if matches:
                    # 将符合条件的文件名添加到列表中
                    self.file_names.append(os.path.join(root, file))
        print(self.file_names)
        return self.file_names


    # 查找是否包含标记信息
    def find_key_word(self, key_flag_infor, line_infor):
        if line_infor.find(key_flag_infor) != -1:
            print('Match')
            return True
        return False

# 字符串如果符合匹配条件,则进行替换
    def replace_key_word(self, line_infor, regexp, target):
        pattern_re = re.compile(regexp)
        match_result = pattern_re.search(line_infor)
        if match_result:
            key_word = "{}".format(match_result.group(1))
            results = re.sub(key_word, target, line_infor)
            print(results)
            return results
        return ''

    def read_infor_by_line(self, path):
        self.file_lines.clear()
        with open(path, "r", encoding="utf-8") as file:
            self.file_lines = file.readlines()
            return True
        return False

    def read_infor_by_line1(self):
        if not os.path.exists(self.file_name):
            return False
        self.file_lines.clear()
        with open(self.file_name, "r", encoding="utf-8") as file:
            self.file_lines = file.readlines()
            return True
        return False

    def write_infor_by_line(self):
        with open(self.file_name, "w", encoding="utf-8") as file:
            file.writelines(self.file_lines)

    def rename_file(self):
        now = datetime.now()
        newname = now.strftime("_%Y%m%d%H%M%S.bak")
        print(self.file_name + newname)
        os.rename(self.file_name, self.file_name + newname)

    def find_and_replace_key_word(self, key_flag_infor, regexp, target):
        start_match = False
        for i, line in enumerate(self.file_lines):
            if not start_match:
                if self.find_key_word(key_flag_infor, line):
                    start_match = True
                if key_flag_infor == '':
                    start_match = True
            if not start_match:
                continue
            new_line = self.replace_key_word(line, regexp, target)
            if new_line != '':
                print(new_line)
                self.file_lines[i] = new_line
                return True

        return False

    def find_and_Record_key_word(self, key_flag_infor, start, end):
        start_match = False
        start_matched = False
        tmp =''
        for i, line in enumerate(self.file_lines):
            if not start_match:
                if self.find_key_word(key_flag_infor, line):
                    start_match = True
                if key_flag_infor == '':
                    start_match = True
            tmp = line.replace('<', '&lt;')
            tmp = tmp.replace('>', '&gt')
            tmp = tmp.replace(' ', '&emsp;')
            tmp = tmp.replace('\t', '&emsp;&emsp;&emsp;&emsp;')
            if not start_match:
                continue
            if not start_matched:
                if self.find_key_word(start, line):
                    start_matched = True
                    self.line_record.append(tmp)
            else:
                self.line_record.append(tmp)

            if self.find_key_word(end, line):
                self.line_record.append(tmp)
                return True
        return False

    def get_key_word_from_xml(self, file_dir, key_flag_infor, start, end):
        self.find_file_by_regexp(file_dir, '', "(\.[xm|XML])")
        for file_name in self.file_names:
            print(file_name)
            tmp = "{}".format(file_name)
            self.read_infor_by_line(tmp)
            self.line_record.append(tmp)
            if not self.find_and_Record_key_word(key_flag_infor, start, end):
                return False
            print(self.line_record)
        return True


class WinGUI(Tk):
    def __init__(self):
        super().__init__()
        self.__win()
        self.tk_button_run = self.__tk_button_run(self)
        self.tk_button_select = self.__tk_button_Select_dsl(self)
        self.tk_input_path = self.__tk_input_path(self)
        self.tk_button_lrxiumtm = self.__tk_button_lrxiumtm(self)
        self.tk_input_log = self.__tk_input_log(self)
        self.excel_path = excel_path
        self.dsl_path = dsl_path
        self.excel_colum_num = 0


    def __win(self):
        self.title(app_name)
        # 设置窗口大小、居中
        width = 1200
        height = 200
        screenwidth = self.winfo_screenwidth()
        screenheight = self.winfo_screenheight()
        geometry = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
        self.geometry(geometry)

        self.resizable(width=False, height=False)

    def scrollbar_autohide(self, vbar, hbar, widget):
        """自动隐藏滚动条"""

        def show():
            if vbar: vbar.lift(widget)
            if hbar: hbar.lift(widget)

        def hide():
            if vbar: vbar.lower(widget)
            if hbar: hbar.lower(widget)

        hide()
        widget.bind("<Enter>", lambda e: show())
        if vbar: vbar.bind("<Enter>", lambda e: show())
        if vbar: vbar.bind("<Leave>", lambda e: hide())
        if hbar: hbar.bind("<Enter>", lambda e: show())
        if hbar: hbar.bind("<Leave>", lambda e: hide())
        widget.bind("<Leave>", lambda e: hide())

    def v_scrollbar(self, vbar, widget, x, y, w, h, pw, ph):
        widget.configure(yscrollcommand=vbar.set)
        vbar.config(command=widget.yview)
        vbar.place(relx=(w + x) / pw, rely=y / ph, relheight=h / ph, anchor='ne')

    def h_scrollbar(self, hbar, widget, x, y, w, h, pw, ph):
        widget.configure(xscrollcommand=hbar.set)
        hbar.config(command=widget.xview)
        hbar.place(relx=x / pw, rely=(y + h) / ph, relwidth=w / pw, anchor='sw')

    def create_bar(self, master, widget, is_vbar, is_hbar, x, y, w, h, pw, ph):
        vbar, hbar = None, None
        if is_vbar:
            vbar = Scrollbar(master)
            self.v_scrollbar(vbar, widget, x, y, w, h, pw, ph)
        if is_hbar:
            hbar = Scrollbar(master, orient="horizontal")
            self.h_scrollbar(hbar, widget, x, y, w, h, pw, ph)
        self.scrollbar_autohide(vbar, hbar, widget)

    def __tk_button_Select_dsl(self, parent):
        btn = Button(parent, text="选择文件夹", command=self.get_dsl_path)
        btn.place(x=1100, y=96, width=93, height=40)
        return btn

    def __tk_button_run(self, parent):
        btn = Button(parent, text="运行", command=self.run)
        btn.place(x=450, y=140, width=300, height=60)
        return btn

    def __tk_input_path(self, parent):
        ipt = Entry(parent, )
        ipt.place(x=4, y=21, width=1090, height=40)
        ipt.delete(0, tkinter.END)  # 删除现有内容
        ipt.insert(0, excel_path)
        return ipt

    def __tk_button_lrxiumtm(self, parent):
        btn = Button(parent, text="选择文件", command=self.get_path)
        btn.place(x=1100, y=23, width=95, height=40)
        return btn

    def __tk_input_log(self, parent):
        ipt = Entry(parent, )
        ipt.place(x=5, y=95, width=1090, height=40)
        ipt.delete(0, tkinter.END)  # 删除现有内容
        ipt.insert(0, dsl_path)
        return ipt

    def read_src_data_excel(self, excel_path):
        # 读取Excel文件
        df = pd.read_excel(excel_path, engine='openpyxl')
        return df

    def get_path(self):
        path = filedialog.askopenfilename()
        self.tk_input_path.delete(0, tkinter.END)  # 删除现有内容
        self.tk_input_path.insert(0, path)
        if os.path.exists(path):
           self.excel_path = path
           print(path)
        else:
            self.tk_input_log.delete(0, tkinter.END)  # 删除现有内容
            self.tk_input_log.insert(0, "file not exists")

    def get_dsl_path(self):
        path = filedialog.askdirectory()
        self.tk_input_log.delete(0, tkinter.END)  # 删除现有内容
        self.tk_input_log.insert(0, path)
        if os.path.exists(path):
           self.dsl_path = path
           print(path)
        else:
            self.tk_input_log.delete(0, tkinter.END)  # 删除现有内容
            self.tk_input_log.insert(0, "file not exists")

    def create_html(self, lines):
        print('---')
        print(lines)
        html_infor = []
        html_infor.append('<!DOCTYPE html>\n')
        html_infor.append('<html lang="en">\n')
        html_infor.append('<head>\n')
        html_infor.append('<meta charset="UTF-8">\n')
        html_infor.append('<meta name="viewport" content="width=device-width, initial-scale=1.0">\n')
        html_infor.append('<title>Show_Infor</title>\n')
        html_infor.append('</head>\n')
        html_infor.append('<body style="background-color: #1b9b7d;">\n')
        html_infor.append('<table>\n')
        for line in lines:
            tmp = "<tr>\n<td>{}</div></td>\n</tr>\n".format(line)
            html_infor.append(tmp)

        html_infor.append('</table>\n')
        html_infor.append('</body>\n')
        html_infor.append('</html>\n')
        now = datetime.now()
        newname = now.strftime("\\Result_%Y%m%d%H%M%S.html")
        with open(self.dsl_path + newname, "w", encoding="utf-8") as file:
            file.writelines(html_infor)
        os.system("start " + self.dsl_path + newname)
        return


    def run(self):
        print('run  hello')
        pdf = self.read_src_data_excel(self.excel_path)
        replaceopt = ReplaceFileKey(self.dsl_path)
        need_save_file = False
        for index, row in pdf.iterrows():
            print(row['key_flag'])
            key_flag = row['key_flag']
            start = row['start']
            end = row['end']
            tmp = start.replace('<', '&lt;')
            tmp = tmp.replace('>', '&gt')
            replaceopt.line_record.append("<br><br>=================      " + tmp + "    ======================<br><br>")
            if not replaceopt.get_key_word_from_xml(self.dsl_path, key_flag, start, end):
                return
            else:
                need_save_file = True
        if need_save_file:
            self.create_html(replaceopt.line_record)
        if excel_path != self.excel_path:
            write_ini_value(path_infor + 'config.ini', 'excel_path', self.excel_path)
            write_ini_value(path_infor + 'config.ini', 'dsl_path', self.dsl_path)
        print(showinfo(title="TipsInfor", message="=== Done ==="))


class Win(WinGUI):
    def __init__(self, controller):
        self.ctl = controller
        super().__init__()
        self.__event_bind()
        self.__style_config()
        self.ctl.init(self)

    def __event_bind(self):
        pass

    def __style_config(self):
        pass


def read_ini_value(path, key):
    # 创建一个ConfigParser对象
    config = configparser.ConfigParser()

    # 读取INI文件
    config.read(path + 'config.ini')

    # 获取指定section和key的值
    value = config.get(key, 'value')
    print(value)
    return value


def write_ini_value(path, key, value):
    # 创建一个ConfigParser对象
    config = configparser.ConfigParser()

    # 读取INI文件
    config.read(path)

    # 修改指定section和key的值
    config.set(key, 'value', value)

    # 将更改写回INI文件
    with open(path, 'w') as configfile:
        config.write(configfile)
    return True


if __name__ == "__main__":
    stra = []
    stra.append("12w45.html")
    stra.append("12w45.xml")
    stra.append("12w45.XML")
    pattern_re = re.compile("(\.[xm|XML])")
    # 遍历目录及其子目录下所有文件
    for files in stra:
        # 判断文件名是否以"flow"结尾
        matches = pattern_re.search(files)
        if matches:
            # 将符合条件的文件名添加到列表中
            print(files)

    path_infor = os.getcwd()
    path_infor = path_infor + '\\'
    run_dir = path_infor
    ini_path = read_ini_value(path_infor,'current_path')
    app_name = read_ini_value(path_infor, 'app_name')
    excel_path = read_ini_value(path_infor, 'excel_path')
    dsl_path = read_ini_value(path_infor, 'dsl_path')
    print('++:' + path_infor)
    print('++:' + app_name)
    config_path = path_infor + 'config.ini'
    if ini_path != path_infor + 'config.ini':
        write_ini_value(config_path, 'current_path', config_path) # config_path
    win = WinGUI()
    win.mainloop()
=======================config.ini===============================

[app_name]
value = Change_dsl_tool

[current_path]
value = D:\PycharmProjects\pythonProject\GetXMLNodeContent\config.ini

[excel_path]
value = D:\PycharmProjects\pythonProject\GetXMLNodeContent\GetNodeInfor.xlsx

[dsl_path]
value = D:\PycharmProjects\pythonProject\GetXMLNodeContent\DIR

========================GetNodeInfor.xlsx=======================

indexkey_flagstartend
1hello1<test1></test1>
2hello2<test2></test2>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值