python-xml-拼接
from xml.etree import ElementTree as ET
import xml
def joinXmlElement(**kwargs):
"""
根据输入的字典数据 生成xmlElement 对象
:return:
"""
# subElement = ET.SubElement(element, "Array", attrib={'Qty': f"{len(subData):>04}"}) #
element = kwargs.get("element", None)
data = kwargs['data'] # 拼接的数据
root = kwargs.get("root", {"tag": "Value"})
# 父节点 Value
if element is None:
element = ET.Element(root["tag"], attrib=root.get("attribute", {}))
for tag, value in data.items():
# 添加特殊字符,解决重复tag
tag = tag.replace("#", "")
attribute, text, child = value.get("attribute", {}), value.get("text", None), value.get("child", None)
# #
# 添加子节点
subElement = ET.SubElement(element, tag, attrib=attribute)
# 如果 text 不为空则添加文本
# # text
if text is not None:
subElement.text = text
# 如果有字节点,则递归调用
if child is not None:
joinXmlElement(element=subElement, data=child)
# 生成xml 文件 方便查看,可注释
element = ET.ElementTree(element)
if isinstance(element, ET.ElementTree):
element.write('result.xml', encoding='utf-8')
return element
###### 示例
data = {"jenkins.plugins.http__request.HttpRequest": {"attribute":{"plugin": "http_request@1.9.0"}},
"url": {"text": "Test"},
"ignoreSslErrors": {"text": "false"}}
response = joinXmlElement(data=data)