python转xml为json

以下代码取自获取PA防火墙策略XML文件并转为JSON文件的场景:
通过PA防火墙API获取防火墙策略

防火墙策略xpath为./result/security/rules/entry

以下代码实现将所有entry即策略与策略相关属性转为json对象并存储至文件

python 复制代码
import xml.etree.ElementTree as ET
import requests
import json

entries_XPath = './result/security/rules/entry'

# xml"对象"转字典
def element_to_dict(element):
    result = {}
    if element.tag == 'entry':
         result['name'] = element.attrib.get('name')
         result['uuid'] = element.attrib.get('uuid')
    if len(element) == 0:
        return element.text
    for child in element:
        child_data = element_to_dict(child)
        if child.tag in result:
            if type(result[child.tag]) is list:
                result[child.tag].append(child_data)
            else:
                result[child.tag] = [result[child.tag], child_data]
        else:
            result[child.tag] = child_data
    return result

# xml转json
def transfer_xml_to_json(xml_policy_response):
    root = ET.fromstring(xml_policy_response)
    entries = root.findall(entries_XPath)
    json_policy_response = [element_to_dict(entry) for entry in entries]
    return json_policy_response


if __name__ == '__main__':
    get_api_key(firewall_ip, username, password)
    xml_policy_response = get_security_policy(firewall_ip, api_key)
    json_policy_response = transfer_xml_to_json(xml_policy_response.text)
    with open('rules.json', 'w') as f:
        json.dump(json_policy_response, f)
            
相关推荐
用户11481867894843 分钟前
水印的实现方式逻辑
前端·python
贾公子8 分钟前
从单条内容到账号维度——AIGC 风险评分的工程实现
后端·python
yangmu32031 小时前
编程语言发展简史:从机器指令到智能协作
开发语言
木头左2 小时前
【Python】不点浏览器发博客:逆向 CSDN 创作中心接口做 md-publish 技能
python·自动化·api
Tt有了t2 小时前
设计模式速查
java·python·设计模式
deepseek233 小时前
Python日志拖慢请求?QueueHandler排队、丢失与退出实测
python·性能优化·logging·后端开发·queuehandler
用户91294046848423 小时前
Codex 从零到能交付(05):第一次改代码:生成一个文件清单脚本
python
Dmz丶3 小时前
前端转 AI 100 天 Day 38:Token 管理与成本优化——别让 API 账单爆炸
python
Pniubi3 小时前
Java为什么要分堆和栈
java·开发语言
用户298698530144 小时前
Python 自动化处理 Word 页眉页脚的几种典型场景
后端·python·api