XML 响应没有在 python 中被解析

我正在使用 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>

提前致谢。


慕仙森
浏览 124回答 1
1回答

慕森王

见下文(解析效果很好)import xml.etree.ElementTree as ETxml = '''<?xml version="1.0" encoding="utf-8"?>&nbsp; &nbsp; &nbsp; &nbsp; <DocumentElement>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <EcardInformation>https://integration.medibuddy.in/MediAssistAPI/DownloadEcard/4021172954/name/123</EcardInformation>&nbsp; &nbsp; &nbsp; &nbsp; </DocumentElement>'''root = ET.fromstring(xml)ecard_info = root.getchildren()[0]print(ecard_info.text)输出https://integration.medibuddy.in/MediAssistAPI/DownloadEcard/4021172954/name/123
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python