我得到XML作为响应,所以我想解析它。我尝试了许多python库,但没有得到我想要的结果。所以如果你能帮忙的话,它会很感激的。
以下代码返回None
xmlResponse = ET.fromstring(context.response_document)
a = xmlResponse.findall('.//Body')
print(a)示例XML数据:
<S:Envelope
xmlns:S="http://www.w3.org/2003/05/soap-envelope">
<S:Header>
<wsa:Action s:mustUnderstand="1"
xmlns:s="http://www.w3.org/2003/05/soap-envelope"
xmlns:wsa="http://www.w3.org/2005/08/addressing">urn:ihe:iti:2007:RegistryStoredQueryResponse
</wsa:Action>
</S:Header>
<S:Body>
<query:AdhocQueryResponse status="urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Success"
xmlns:query="urn:oasis:names:tc:ebxml-regrep:xsd:query:3.0">
<rim:RegistryObjectList
xmlns:rim="u`enter code here`rn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0"/>
</query:AdhocQueryResponse>
</S:Body>
</S:Envelope>我想从它身上得到地位。如果你能建议一些图书馆的改变,那么请帮助我。谢谢
发布于 2019-10-31 21:04:18
给定以下基本代码:
import xml.etree.ElementTree as ET
root = ET.fromstring(xml)让我们在此基础上构建以获得您想要的输出。
.//Body x路径的初始查找不返回任何结果,因为它不存在于您的XML响应中。
XML中的每个标记都有一个与其关联的命名空间。有关xml名称空间的更多信息可以找到这里。
考虑使用xmlns值(xml-命名空间)的以下行:
<S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope">命名空间S的值设置为http://www.w3.org/2003/05/soap-envelope。
将S中的{S}Envelope替换为上面设置的值将为您提供要在XML中找到的结果标记:
root.find('{http://www.w3.org/2003/05/soap-envelope}Envelope') #top most node我们也需要为<S:Body>做同样的事情。
要获取<S:Body>元素及其子节点,可以执行以下操作:
body_node = root.find('{http://www.w3.org/2003/05/soap-envelope}Body')
for response_child_node in list(body_node):
print(response_child_node.tag) #tag of the child node
print(response_child_node.get('status')) #the status you're looking for产出:
{urn:oasis:names:tc:ebxml-regrep:xsd:query:3.0}AdhocQueryResponse
urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:SuccessAlternatively
您还可以使用以下方法直接查找XML中的所有 {query}AdhocQueryResponse:
response_nodes = root.findall('.//{urn:oasis:names:tc:ebxml-regrep:xsd:query:3.0}AdhocQueryResponse')
for response in response_nodes:
print(response.get('status'))产出:
urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Successhttps://stackoverflow.com/questions/58642152
复制相似问题