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)
            
相关推荐
素界UI设计43 分钟前
建筑行业变革:用Three.js构建BIM数据可视化孪生平台
开发语言·javascript·信息可视化
深盾安全1 小时前
Python 装饰器详解
python
王廷胡_白嫖帝1 小时前
Qt个人通讯录项目开发教程 - 从零开始构建联系人管理系统
开发语言·qt
前端小趴菜051 小时前
python - 数据类型转换
python
跟橙姐学代码2 小时前
学Python必须迈过的一道坎:类和对象到底是什么鬼?
前端·python
卡洛斯(编程版2 小时前
(1) 哈希表全思路-20天刷完Leetcode Hot 100计划
python·算法·leetcode
疯狂的代M夫2 小时前
C++对象的内存布局
开发语言·c++
mit6.8243 小时前
Linux下C#项目构建
开发语言·c#
FreakStudio3 小时前
一文速通 Python 并行计算:教程总结
python·pycharm·嵌入式·面向对象·并行计算
群联云防护小杜3 小时前
从一次 DDoS 的“死亡回放”看现代攻击链的进化
开发语言·python·linq