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)
            
相关推荐
txinyu的博客4 分钟前
HTTP服务实现用户级窗口限流
开发语言·c++·分布式·网络协议·http
代码村新手5 分钟前
C++-类和对象(上)
开发语言·c++
全栈小精灵13 分钟前
Winform入门
开发语言·机器学习·c#
心静财富之门14 分钟前
退出 for 循环,break和continue 语句
开发语言·python
txinyu的博客16 分钟前
map和unordered_map的性能对比
开发语言·数据结构·c++·算法·哈希算法·散列表
WJSKad123521 分钟前
YOLO11-FDPN-DASI实现羽毛球拍与球的实时检测与识别研究
python
幻云201030 分钟前
Next.js之道:从入门到精通
人工智能·python
Mr -老鬼31 分钟前
Rust适合干什么?为什么需要Rust?
开发语言·后端·rust
0和1的舞者32 分钟前
GUI自动化测试详解(三):测试框架pytest完全指南
自动化测试·python·测试开发·自动化·pytest·测试
予枫的编程笔记34 分钟前
【Java集合】深入浅出 Java HashMap:从链表到红黑树的“进化”之路
java·开发语言·数据结构·人工智能·链表·哈希算法