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)
            
相关推荐
C+-C资深大佬2 分钟前
在PyCharm中创建虚拟环境的具体步骤是什么?
ide·python·pycharm
iCxhust16 分钟前
c#多串口重量采集上位机程序
开发语言·汇编·c#·微机原理·8088单板机
QK_0037 分钟前
volatile 关键字核心作用
开发语言
Dxy123931021638 分钟前
Python Tensor 向量入门:从零理解深度学习的“数据语言“
开发语言·python·深度学习
林森lsjs1 小时前
【日耕一题】3. 通过键盘输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
java·开发语言
yzy851 小时前
数据同步工具 -- syncthing
开发语言
catchadmin1 小时前
PHP 应用 security.txt 漏洞披露实践
开发语言·php
糖果店的幽灵1 小时前
LangChain 1.3 完全教程:从入门到精通-Part 11: Tools(工具系统)
开发语言·langchain·c#
夜勤月1 小时前
AQS 与 ThreadPoolExecutor 深度拆解:JDK 高并发底层设计精髓
android·java·开发语言
luj_17681 小时前
R语言生态优势与学习曲线分析
c语言·开发语言·网络·经验分享·算法