我有以下 xml 字符串,我想从 Python 中的 ReturnCode 中获取值。我怎样才能轻松做到这一点?
我试过使用元素树:
tree = ET.ElementTree(ET.fromstring(response))
root = tree.getroot()
<API>
<Result>
<ErrorCode ErrorType=\"Success\">0</ErrorCode>
<ReturnCode>0</ReturnCode>
</Result>
<API>
实际的响应值是这样的——
'<API><Result><ErrorCode ErrorType=\"Success\">0</ErrorCode<ReturnCode>0</ReturnCode></Result><API>'
我希望能够将 ReturnCode 中的值用于其他逻辑。
请您参考如下方法:
作为官方文档xml.etree.elementtree .像这样解析您的 xml 文档:
import xml.etree.ElementTree as ET
# root = ET.fromstring(your_xml_content)
# root.tag
body = '<API><Result><ErrorCode ErrorType="Success">0</ErrorCode><ReturnCode>0</ReturnCode></Result></API>'
response = ET.fromstring(body)
result = response.findall('Result')[0]
return_code = result.find('ReturnCode').text
## output '0'
更新:我错过了结果。
