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)
            
相关推荐
RSABLOCKCHAIN1 小时前
AI Agents in LangGraph-2
人工智能·python
WA内核拾荒者2 小时前
WhatsApp 账号异常检测的自动化告警系统设计
数据库·python·自动化
码流怪侠3 小时前
【GitHub】Bend:让 GPU 并行编程像写 Python 一样简单
python·github
魔力女仆3 小时前
分享一个 JS 鼠标跟随贪吃蛇背景库
开发语言·javascript·计算机外设
2401_894915534 小时前
GEO 搜索优化完整源码从零部署:环境配置、集群搭建全流程
开发语言·python·tcp/ip·算法·unity
麻瓜老宋4 小时前
AI开发C语言应用按步走,表达式计算器calc的第二十二步,分号赋值链式修复、TOKEN_ASSIGN
c语言·开发语言·atomcode
zhiSiBuYu05175 小时前
Python3 模块开发与应用实战指南
python
颜x小6 小时前
[C#] C++与c#语法对比
开发语言·c++·c#
databook6 小时前
用方差阈值过滤掉“惰性特征”
python·机器学习·scikit-learn