我正在使用 python 中的请求库从 API 获取 XML 响应。但是,当我按照此处接受的答案解析 python 中的响应时。我正在使用以下代码。 try: # Prepare request payload = "<DataRequest><groupcode>ABC</groupcode><employeeno>123456</employeeno></DataRequest>" url = config['SF_Credentials']['end_point'] headers = {"Authorization": config['SF_Credentials']['authorization'], "Content-Type":"text/xml"} response = requests.post(url, data = payload, headers= headers) if response.status_code >300: print('error in getting ecard', response.text) xml_data = ET.fromstring(response.text) print(dir(xml_data), xml_data.text) print('done') except Exception as e: print('exception in getting ecard', e)但print(xml_data.text)给出输出无。我的 API 响应是:<?xml version="1.0" encoding="utf-8"?><DocumentElement><EcardInformation>https://integration.medibuddy.in/MediAssistAPI/DownloadEcard/4021172954/name/123</EcardInformation></DocumentElement>'与上面提到的问题不同,我使用的是邮政电话。在这种情况下有什么不同吗?还是我还缺少其他东西?此外,的输出response.text是<?xml version="1.0" encoding="utf-8"?><DocumentElement><EcardInformation>https://integration.medibuddy.in/MediAssistAPI/DownloadEcard/4021172954/Name/1234</EcardInformation></DocumentElement>提前致谢。
1 回答

慕森王
TA贡献1777条经验 获得超3个赞
见下文(解析效果很好)
import xml.etree.ElementTree as ET
xml = '''<?xml version="1.0" encoding="utf-8"?>
<DocumentElement>
<EcardInformation>https://integration.medibuddy.in/MediAssistAPI/DownloadEcard/4021172954/name/123</EcardInformation>
</DocumentElement>'''
root = ET.fromstring(xml)
ecard_info = root.getchildren()[0]
print(ecard_info.text)
输出
https://integration.medibuddy.in/MediAssistAPI/DownloadEcard/4021172954/name/123
添加回答
举报
0/150
提交
取消