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)
            
相关推荐
E_ICEBLUE2 小时前
如何提取 Word 文档中的表格并导出为 Excel(Python 教程)
python·word·excel
极光代码工作室2 小时前
基于NLP的智能问答系统设计
python·深度学习·自然语言处理·nlp
平凡但不平庸的码农3 小时前
Go context 包详解
开发语言·后端·golang
隐士Xbox3 小时前
c++ 指针的用法
开发语言·c++·计算机视觉
lbb 小魔仙3 小时前
Python 多模态 AI 应用开发实战:用 GPT-4o + LangChain 构建智能视觉助手
人工智能·python·langchain
江南十四行3 小时前
Python元类编程——从type到metaclass的深度探索
开发语言·python
众乐乐_20083 小时前
PHP 的进程 fork 机制
开发语言·php
yujunl3 小时前
U9 WCF调试的一个坑
开发语言
lly2024063 小时前
Scala 模式匹配
开发语言
2zcode3 小时前
基于MATLAB卷积神经网络的多颜色车牌识别系统设计与实现
开发语言·matlab·cnn