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)
            
相关推荐
维克兜率天2 分钟前
【维克】布林带:通道类指标的“量化基石“
人工智能·python·算法
Evand J8 分钟前
【CIR系列2】UWB视距(LOS)与非视距(NLOS)信道冲激响应(CIR)建模与对比,MATLAB
开发语言·matlab·信号处理·nlos·cir
风落青芜11 分钟前
C++入门:类和对象(二)
开发语言·数据结构·c++·算法
向科→向总工→空间动态计系统37 分钟前
机器人大脑系统
开发语言·人工智能·python·机器人
染指111038 分钟前
194.DeepAgents-在DeepAgents中使用自定义沙盒环境OpenSandBox
网络·人工智能·python·langchain·deepagents
一只QAQ44 分钟前
c语言八股
c语言·开发语言
wuyk5551 小时前
AI 时代的嵌入式该怎么学-11-C不是语法是对内存的显式建模
c语言·开发语言·stm32·单片机·嵌入式硬件·mcu·算法
吃我一窝jio1 小时前
字节流与字符流深度解析
java·开发语言·笔记
风落青芜2 小时前
C++入门:类和对象(三)
开发语言·数据结构·c++·算法
m0_646429972 小时前
LangGraph 学习笔记(一):StateGraph 与状态管理
python·langgraph