使用pythonetree解析soap响应返回空字典

2024-10-03 19:26:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试过从下面的xml/soap响应解析sessionId字段,但所有子属性字典都是空的:

#!/usr/bin/python

import requests
from xml.etree import ElementTree
from xml.dom import minidom

url="http://172.16.46.85:8080/CAI3G1.2/services/CAI3G1.2"

headers = {'content-type': 'text/xml'}

body = """<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"             xmlns:cai3="http://schemas.ericsson.com/cai3g1.2/">
    <soapenv:Body>
            <cai3:Login>
                    <cai3:userId>admin</cai3:userId>
                    <cai3:pwd>admin</cai3:pwd>
            </cai3:Login>
    </soapenv:Body>
</soapenv:Envelope>
"""

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

print 'content : ' + str(response.content)
print '##################################################'
print 'text : ' + str(response.text)
print '##################################################'

root = ElementTree.fromstring(response.content)

for child in root.iter('*'):
    print 'child tag : ' + child.tag
    print 'child attrib : ' + str(child.attrib)

print '##################################################'

for child in root:
    print child.tag, child.attrib

print '##################################################'

下面是执行结果,我不是在寻求使用re的任何解决方案,我知道可以使用re库来完成,我想知道如何使用etree实现它(如果可以做到):

^{pr2}$

Tags: textimportchildhttpresponsetagrootxml
1条回答
网友
1楼 · 发布于 2024-10-03 19:26:32

除了xmlns,所有标记都没有属性,ElemenTree似乎排除了这个属性,因为它是一些“众所周知”的信息。如果您需要sessionId标记,您应该已经知道它是http://schemas.ericsson.com/cai3g1.2/名称空间的一部分。在

使用Element.find()可以使用XPath表达式搜索特定的标记。例如:

from xml.etree import ElementTree
s = '''<?xml version='1.0' encoding='UTF-8'?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><ns2:LoginResponse xmlns:ns2="http://schemas.ericsson.com/cai3g1.2/"><ns2:sessionId>c70f2a0f7e7d4c5084bea857715e2d10</ns2:sessionId><ns2:baseSequenceId>306324732</ns2:baseSequenceId></ns2:LoginResponse></S:Body>    </S:Envelope>'''
root = ElementTree.fromstring(s)
ns = {'cai3g1.2': 'http://schemas.ericsson.com/cai3g1.2/'}
root.find('.//cai3g1.2:sessionId', ns).text
'c70f2a0f7e7d4c5084bea857715e2d10'
root.find('.//cai3g1.2:baseSequenceId', ns).text
'306324732'

相关问题 更多 >