python-xml-解析
from xml.etree import ElementTree as ET
import xml
def joinXmlElement(**kwargs):
"""
根据输入的字典数据 生成xmlElement 对象
:param element: 父节点
:param data: 字典数据
:return:
"""
element = kwargs.get("element", None)
data = kwargs['data']
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.replace("#", "")
attribute, text, child = value.get("attribute", {}), value.get("text", None), value.get("child", {})
subElement = ET.SubElement(element, tag, attrib=attribute)
if text is not None:
subElement.text = text
joinXmlElement(element=subElement, data=child)
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))