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)
            
相关推荐
阿里嘎多学长6 分钟前
2026-07-14 GitHub 热点项目精选
开发语言·程序员·github·代码托管
中微极客11 分钟前
解锁LLM开发全栈能力:Python + LangChain + RAG 工程实战指南
人工智能·python·langchain
hhzz31 分钟前
Barbershop:基于GAN和分割Mask的图像合成技术——从理论到实战全解析
图像处理·人工智能·python·深度学习·计算机视觉
charlie1145141911 小时前
Cinux: 为大内核铺路
开发语言·c++·操作系统·现代c++
2501_914245931 小时前
C语言设计模式详解:从理论到实践的完整指南
c语言·开发语言·设计模式
Hazenix2 小时前
Go 指南:一篇文章速通 Golang
开发语言·后端·golang
灯澜忆梦2 小时前
GO_复合类型---指针
开发语言·后端·golang
Ulyanov2 小时前
雷达导引头Python仿真框架:GPU加速、6-DOF模型与半实物仿真接口
开发语言·python·雷达信号处理·雷达导引头
列逍2 小时前
博客系统测试
自动化测试·python·性能测试
名字还没想好☜3 小时前
Go slice 的 append 陷阱:共享底层数组导致的数据串改
开发语言·后端·golang·go·slice