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)
            
相关推荐
重生之我在20年代敲代码14 分钟前
strncpy函数的使用和模拟实现
c语言·开发语言·c++·经验分享·笔记
爱上语文15 分钟前
Springboot的三层架构
java·开发语言·spring boot·后端·spring
waterHBO1 小时前
python 爬虫 selenium 笔记
爬虫·python·selenium
编程零零七2 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql
2401_858286113 小时前
52.【C语言】 字符函数和字符串函数(strcat函数)
c语言·开发语言
铁松溜达py3 小时前
编译器/工具链环境:GCC vs LLVM/Clang,MSVCRT vs UCRT
开发语言·网络
everyStudy3 小时前
JavaScript如何判断输入的是空格
开发语言·javascript·ecmascript
AIAdvocate4 小时前
Pandas_数据结构详解
数据结构·python·pandas
小言从不摸鱼4 小时前
【AI大模型】ChatGPT模型原理介绍(下)
人工智能·python·深度学习·机器学习·自然语言处理·chatgpt
C-SDN花园GGbond5 小时前
【探索数据结构与算法】插入排序:原理、实现与分析(图文详解)
c语言·开发语言·数据结构·排序算法