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)
            
相关推荐
Mr YiRan27 分钟前
C++面向对象继承与操作符重载
开发语言·c++·算法
Emotional。29 分钟前
2025 年度技术总结与规划:AI 时代的开发者成长之路
人工智能·python·ai·langchain
一只鹿鹿鹿3 小时前
智慧水利一体化建设方案
大数据·运维·开发语言·数据库·物联网
witAI4 小时前
**AI仿真人剧制作软件2025推荐,解锁沉浸式数字内容创作
人工智能·python
没有医保李先生5 小时前
字节对齐的总结
java·开发语言
Elastic 中国社区官方博客5 小时前
使用 Elastic 进行网络监控:统一网络可观测性
大数据·开发语言·网络·人工智能·elasticsearch·搜索引擎·全文检索
Codefengfeng5 小时前
Python Base环境中加包的方法
开发语言·python
清水白石0085 小时前
《Python 编程全景解析:从核心精要到测试替身(Test Doubles)五大武器的实战淬炼》
开发语言·python
如若1236 小时前
AutoDL云服务器 NVIDIA 570驱动 EGL渲染修复全记录
运维·服务器·python
甲枫叶6 小时前
【claude】Claude Code正式引入Git Worktree原生支持:Agent全面实现并行独立工作
java·人工智能·git·python·ai编程