You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用XML API时请求体参数格式化问题求助

解决Python构造XML API请求体的格式化问题

不要手动通过字符串拼接/格式化来生成XML,这种方式容易出现缩进混乱、特殊字符未转义、属性格式不规范等问题,推荐使用Python内置的XML库来构建请求体,既能保证格式正确,也更易维护。

方法一:使用xml.etree.ElementTree构建XML(内置库,无需额外安装)

场景1:API接受多顶级元素(与你提供的UI格式一致)

import xml.etree.ElementTree as ET

# 构建Employee节点
employee = ET.Element("Employee")
employee_id = ET.SubElement(employee, "EmployeeId")
employee_id.set("ID", "ABCD")  # 设置属性

# 构建Time和Date节点
time_elem = ET.Element("Time")
time_elem.text = "10:00"
date_elem = ET.Element("Date")
date_elem.text = "10/02/2019"

# 将各节点转为字符串并拼接
employee_str = ET.tostring(employee, encoding='unicode')
time_str = ET.tostring(time_elem, encoding='unicode')
date_str = ET.tostring(date_elem, encoding='unicode')

body = employee_str + time_str + date_str

场景2:API要求单根XML节点(规范XML结构)

大多数XML API要求有唯一根节点,你可以将所有元素包裹在一个根节点下:

import xml.etree.ElementTree as ET

# 创建根节点
root = ET.Element("Request")

# 构建Employee子节点
employee = ET.SubElement(root, "Employee")
employee_id = ET.SubElement(employee, "EmployeeId")
employee_id.set("ID", "ABCD")

# 构建Time和Date子节点
ET.SubElement(root, "Time").text = "10:00"
ET.SubElement(root, "Date").text = "10/02/2019"

# 转为字符串
body = ET.tostring(root, encoding='unicode')

美化XML缩进(可选)

如果需要和UI格式一致的缩进,可以用xml.dom.minidom来格式化:

import xml.etree.ElementTree as ET
import xml.dom.minidom

root = ET.Element("Request")
employee = ET.SubElement(root, "Employee")
employee_id = ET.SubElement(employee, "EmployeeId")
employee_id.set("ID", "ABCD")
ET.SubElement(root, "Time").text = "10:00"
ET.SubElement(root, "Date").text = "10/02/2019"

# 生成带缩进的格式化XML
rough_string = ET.tostring(root, encoding='unicode')
parsed = xml.dom.minidom.parseString(rough_string)
body = parsed.toprettyxml(indent="    ")  # 缩进用4个空格,可按需调整

关于编码问题

发送请求时,需要将字符串格式的XML转为字节流,通常用UTF-8编码:

# 假设使用requests库发送请求
import requests

headers = {"Content-Type": "application/xml; charset=utf-8"}
response = requests.post("你的API地址", data=body.encode('utf-8'), headers=headers)

为什么不推荐手动拼接字符串?

  • 缩进控制麻烦:你之前用format生成的XML会带有原始字符串里的大量冗余缩进,strip()和replace()很难精准处理;
  • 特殊字符风险:如果参数包含<、&等XML特殊字符,手动拼接会直接导致XML无效,而XML库会自动处理转义;
  • 属性格式不规范:规范XML要求属性值加引号(比如ID="ABCD"),你提供的UI示例虽然没加,但API可能兼容,用库生成会遵循规范,避免潜在问题。

内容的提问来源于stack exchange,提问作者Mixter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 08:45:32