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)
            
相关推荐
英英_3 分钟前
优化 MATLAB MapReduce 程序性能:从基础调优到进阶提速
开发语言·matlab·mapreduce
LSL666_9 分钟前
BaseMapper——新增和删除
java·开发语言·mybatis·mybatisplus
傻啦嘿哟9 分钟前
Python操作Redis:高效缓存设计与实战
redis·python·缓存
Fairy要carry13 分钟前
面试-Agent任务编排怎么处理?
网络·python·面试
xiangpanf20 分钟前
PHP vs C语言:30字解析两大编程语言差异
c语言·开发语言·php
wdfk_prog22 分钟前
MAX14830 可移植 C 驱动实现分析:一个适合多串口扩展场景的开源基础版本
c语言·开发语言·开源
Elnaij27 分钟前
从C++开始的编程生活(22)——红黑树
开发语言·c++
EW Frontier28 分钟前
【UAV识别】基于分层学习的射频无人机检测与识别技术,准确率达99%!【附python代码】
python·无人机·无人机信号识别
.select.33 分钟前
STL下常见容器底层数据结构
开发语言·c++
于先生吖35 分钟前
基于 Java 开发短剧系统:完整架构与核心功能实现
java·开发语言·架构