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)
            
相关推荐
Python×CATIA工业智造2 小时前
Frida RPC高级应用:动态模拟执行Android so文件实战指南
开发语言·python·pycharm
onceco2 小时前
领域LLM九讲——第5讲 为什么选择OpenManus而不是QwenAgent(附LLM免费api邀请码)
人工智能·python·深度学习·语言模型·自然语言处理·自动化
我叫小白菜3 小时前
【Java_EE】单例模式、阻塞队列、线程池、定时器
java·开发语言
狐凄3 小时前
Python实例题:基于 Python 的简单聊天机器人
开发语言·python
weixin_446122464 小时前
JAVA内存区域划分
java·开发语言·redis
悦悦子a啊4 小时前
Python之--基本知识
开发语言·前端·python
QuantumStack5 小时前
【C++ 真题】P1104 生日
开发语言·c++·算法
whoarethenext5 小时前
使用 C++/OpenCV 和 MFCC 构建双重认证智能门禁系统
开发语言·c++·opencv·mfcc
笑稀了的野生俊6 小时前
在服务器中下载 HuggingFace 模型:终极指南
linux·服务器·python·bash·gpu算力
Naiva6 小时前
【小技巧】Python+PyCharm IDE 配置解释器出错,环境配置不完整或不兼容。(小智AI、MCP、聚合数据、实时新闻查询、NBA赛事查询)
ide·python·pycharm