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)
            
相关推荐
Lu Yao_16 分钟前
用golang实现二叉搜索树(BST)
开发语言·数据结构·golang
沐土Arvin39 分钟前
前端图片上传组件实战:从动态销毁Input到全屏预览的全功能实现
开发语言·前端·javascript
找不到、了42 分钟前
Spring-Beans的生命周期的介绍
java·开发语言·spring
(・Д・)ノ1 小时前
python打卡day29
开发语言·python
若水晴空初如梦1 小时前
QT聊天项目DAY11
开发语言·qt
有杨既安然2 小时前
Python高级特性深度解析:从熟练到精通的跃迁之路
开发语言·python·数据挖掘·flask
蹦蹦跳跳真可爱5892 小时前
Python----神经网络(《Searching for MobileNetV3》论文概括和MobileNetV3网络)
人工智能·python·深度学习·神经网络
妄想成为master2 小时前
如何完美安装GPU版本的torch、torchvision----解决torch安装慢 无法安装 需要翻墙安装 安装的是GPU版本但无法使用的GPU的错误
人工智能·pytorch·python·环境配置
wanfeng_092 小时前
CMS(plone / joomla 搭建测试)
python·多站点·本地搭建·joomla·plone
浩皓素2 小时前
Python函数库调用实战:以数据分析为例
python