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)
            
相关推荐
m0_733565461 天前
mysql数据库执行全量备份影响业务_利用xtrabackup实现无锁备份
jvm·数据库·python
2401_880071401 天前
golang如何编写DNS查询工具_golang DNS查询工具编写大全
jvm·数据库·python
海盗12341 天前
C#在Distinct()中使用IEqualityComparer<T>
开发语言·c#
Vertira1 天前
python 配置PostgreSQL 数据库
开发语言·python
m0_591364731 天前
JavaScript中Object-hasOwn作为现代安全检测方案
jvm·数据库·python
m0_624578591 天前
html标签怎么避免标签嵌套错误_div不能放在p内原因【详解】
jvm·数据库·python
Highcharts.js1 天前
Highcharts 纯 JavaScript 图表库深度使用评测
开发语言·前端·javascript·功能测试·ecmascript·highcharts·技术评测
2301_769340671 天前
怎样导出用于负载测试的样本数据_LIMIT限制数据量提取
jvm·数据库·python
瑶池酒剑仙1 天前
C++类和对象完全指南:从封装继承多态到内存布局的面向对象宝典(雨夜论道)
c语言·开发语言·c++·visual studio
三品吉他手会点灯1 天前
C语言学习笔记 - 27.C编程预备计算机专业知识 - 什么是字节
c语言·开发语言·笔记·学习