首页 > 解决方案 > 如何将动态值传递给 xml 文件?

问题描述

我们在 python 中使用 SOAP API。我们需要动态传递请求 xml 文件中的值。

test.xml文件:

<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
    <Body>
        <Add xmlns="http://tempuri.org/">
            <intA>3</intA>
            <intB>4</intB>
        </Add>
    </Body>
</Envelope>

Python脚本:

from bs4 import BeautifulSoup
import requests
import xml.etree.ElementTree as ET
import lxml
url="http://www.dneonline.com/calculator.asmx?WSDL"
headers = {'content-type': 'text/xml'}
xmlfile = open('test.xml','r')
body = xmlfile.read()


response = requests.post(url,data=body,headers=headers)

print(response.text)

我们需要从 python 动态传递 intA 和 intB。

标签: pythonxmlxml-parsing

解决方案


您可以使用格式字符串方法。您可以在 xml 文件中指定位置/关键字参数。在进行请求调用时,您可以传递这些参数的值。

以下是您的 test.xml 文件的外观:

<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
    <Body>
        <Add xmlns="http://tempuri.org/">
            <intA>{first_number}</intA>
            <intB>{second_number}</intB>
        </Add>
    </Body>
</Envelope>

在您的 Python 脚本中,您可以加载 xml 文件,并且在发出帖子请求时,可以传递参数。方法如下:

import requests

url = "http://www.dneonline.com/calculator.asmx?WSDL"
headers = {'content-type': 'text/xml'}
xmlfile = open('test.xml', 'r')
body = xmlfile.read()

response = requests.post(url, data=body.format(first_number=1, second_number=4), headers=headers)

print(response.text)

推荐阅读