python-xml-解析

python-xml-解析

# -*- coding: utf-8 -*-
from xml.etree import ElementTree as ET
import xml


def joinXmlElement(**kwargs):
    """
    根据输入的字典数据 生成xmlElement 对象


    :param element: 父节点
    :param data: 字典数据
    :return:
    """
    # subElement = ET.SubElement(element, "Array", attrib={'Qty': f"{len(subData):>04}"}) #

    element = kwargs.get("element", None)
    data = kwargs['data']  # 拼接的数据

    # 根节点,默认为Value
    if element is None:
        if len(data) == 0:
            rootTag = list(data.keys())[0]
            data = list(data.values())[0]
        else:
            rootTag = "Value"
        attrib = data.get('attribute', {})
        element = ET.Element(rootTag, attrib=attrib)
    for tag, value in data.items():
        # 添加特殊字符,解决重复tag
        tag = tag.replace("#", "")
        attribute, text, child = value.get("attribute", {}), value.get("text", None), value.get("child", {})
        # #  <tag attribute/>
        # 添加子节点
        subElement = ET.SubElement(element, tag, attrib=attribute)
        # 如果 text 不为空则添加文本
        # #  <tag attribute>text</tag>
        if text is not None:
            subElement.text = text
        # 如果有字节点,则递归调用
        joinXmlElement(element=subElement, data=child)
    # # # 生成xml 文件 方便查看,可注释
    # element = ET.ElementTree(element)
    # if isinstance(element, ET.ElementTree):
    #     element.write('result.xml', encoding='utf-8')
    # return element


def analyseXml(**kwargs):
    """
    将xml文件内容或者xml对象解析为 dict 返回

    :return:
    """

    xmlFile = kwargs.get("xmlFile", None)
    xmlString = kwargs.get("xmlString", None)
    xmlObject = kwargs.get("xmlObject", None)

    xmlDict = {}
    if xmlFile is not None:
        xmlObject = ET.parse(xmlFile)
    if xmlString is not None:
        xmlObject = ET.fromstring(xmlString)

    if isinstance(xmlObject, xml.etree.ElementTree.ElementTree):
        root = xmlObject.getroot()
        tag, text, attribute = root.tag, root.text, root.attrib
        if tag in xmlDict:
            tag += "#"
        xmlDict.update({tag: {"text": text, "attribute": attribute, "child": {}}})
        for child in root.getchildren():
            xmlDict[tag]["child"].update(analyseXml(xmlObject=child))
    elif isinstance(xmlObject, xml.etree.ElementTree.Element):
        child = xmlObject.getchildren()
        tag, text, attribute = xmlObject.tag, xmlObject.text, xmlObject.attrib
        if tag in xmlDict:
            tag += "#"
        xmlDict.update({tag: {"text": text, "attribute": attribute, "child": {}}})
        if len(child) != 0:
            for child in xmlObject.getchildren():
                xmlDict[tag]["child"].update(analyseXml(xmlObject=child))
        else:
            return xmlDict
    return xmlDict


if __name__ == '__main__':
    data = {"jenkins.plugins.http__request.HttpRequest": {"attribute": {"plugin": "http_request@1.9.0"},
                                                          "child": {"url": {"text": "child"}}},
            "url": {"text": "Test"},
            "ignoreSslErrors": {"text": "false"}}
    response = joinXmlElement(data=data)
    print(analyseXml(xmlObject=response))
    # {'Value': {'text': None, 'attribute': {}, 'child': {'jenkins.plugins.http__request.HttpRequest': {'text': None, 'attribute': {'plugin': 'http_request@1.9.0'}, 'child': {'url': {'text': 'child', 'attribute': {}, 'child': {}}}}, 'url': {'text': 'Test', 'attribute': {}, 'child': {}}, 'ignoreSslErrors': {'text': 'false', 'attribute': {}, 'child': {}}}}}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值