Files
my_py_tools/utilities/cest_xml.py
2025-10-18 21:32:31 +08:00

96 lines
2.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# @time :2025/9/3 20:49
# @File :cest_xml.py
# Description :
# Author :drygrass
from flask import Flask, request, jsonify
from flask_cors import CORS
import xml.etree.ElementTree as ET
from io import StringIO
app = Flask(__name__)
CORS(app)
@app.route('/api/parse-xml', methods=['POST'])
def parse_xml():
"""
解析上传的XML数据动态提取<inparams>下所有<in>元素的属性
"""
try:
xml_content = request.data.decode('gbk')
root = ET.fromstring(xml_content)
# 核心:使用 findall 查找所有<in>元素,数量未知
in_elements = root.findall('.//inparams/in')
in_params = []
# 遍历所有找到的<in>元素
for in_element in in_elements:
name = in_element.get('name')
value = in_element.get('value')
param_type = in_element.get('type')
width = in_element.get('width', '')
in_params.append({
'name': name,
'value': value,
'type': param_type,
'width': width
})
return jsonify({
'success': True,
'data': in_params, # 这是一个包含所有<in>元素信息的列表
'originalXml': xml_content
})
except ET.ParseError as e:
return jsonify({
'success': False,
'message': f'XML解析失败: {str(e)}。请检查XML格式是否正确如标签是否闭合、特殊字符是否转义等[1,2](@ref)。'
}), 400
except Exception as e:
return jsonify({
'success': False,
'message': f'服务器错误: {str(e)}'
}), 500
@app.route('/api/save-xml', methods=['POST'])
def save_xml():
"""
保存修改后的参数值到XML并返回完整XML内容
"""
try:
data = request.json
original_xml = data['originalXml']
modified_params = data['modifiedParams']
root = ET.fromstring(original_xml)
in_elements = root.findall('.//inparams/in')
# 根据name属性匹配并更新value
for in_element in in_elements:
name = in_element.get('name')
for modified_param in modified_params:
if modified_param['name'] == name:
in_element.set('value', modified_param['value'])
break # 找到并更新后跳出内层循环
modified_xml = ET.tostring(root, encoding='gbk').decode('gbk')
return jsonify({
'success': True,
'modifiedXml': modified_xml,
'message': '保存成功'
})
except Exception as e:
return jsonify({
'success': False,
'message': f'保存失败: {str(e)}'
}), 500
if __name__ == '__main__':
app.run(debug=True, port=5000)