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)
            
相关推荐
攻城狮杰森1 分钟前
Eudic → Maimemo 自动同步工具:欧路词典 & 墨墨背单词
python·api·shell·ai编程·欧路词典·墨墨本单词
( •̀∀•́ )9204 分钟前
高性能拖拽排序
java·开发语言·算法
Ayanami_Reii4 分钟前
进阶数据结构应用-区间最大公约数
开发语言·数据结构·算法·线段树·差分·树状数组·fenwick tree
Vince的修炼之路6 分钟前
用Python将JSON格式文件数据导入到Elasticsearch上
python
哈哈~haha8 分钟前
ui5_Walkthrough_Step 7:JSON Model
json·mvc·module·ui5
不会吉他的肌肉男不是好的挨踢男10 分钟前
LLaMA Factory 训练模型未检测到CUDA环境解决
python·ai·llama
高级盘丝洞18 分钟前
如何通过Powerlink协议读取PLC数据
开发语言·数据库·php
Yang-Never19 分钟前
Open GL ES->EGL渲染环境、数据、引擎、线程的创建
android·java·开发语言·kotlin·android studio
Justinyh19 分钟前
Notion同步到CSDN + 构建Obsidian本地博客系统指南
python·csdn·图床·notion·obsidian·文档同步·piclist
unicrom_深圳市由你创科技19 分钟前
使用 Vue3 + Nest.js 构建前后端分离项目的完整指南
开发语言·javascript·状态模式