如何在python中解析包含带有xml命名空间标记的节点的xml数据?

2024-04-26 21:33:09 发布

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

我得到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>

我想从它身上得到状态。如果你能建议一些图书馆的变化,那么请帮助我。谢谢


Tags: orghttpnameswwwbodyquerytcebxml
1条回答
网友
1楼 · 发布于 2024-04-26 21:33:09

给定以下基本代码:

import xml.etree.ElementTree as ET

root = ET.fromstring(xml)

让我们在此基础上进行构建,以获得所需的输出。你知道吗

.//Bodyx-path的初始查找返回NONE,因为它不存在于XML响应中。你知道吗

XML中的每个标记都有一个与其相关联的命名空间。有关xml名称空间的更多信息可以在here中找到。你知道吗

考虑以下带有xmlns值(xml命名空间)的行:

<S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope">

命名空间S的值设置为http://www.w3.org/2003/05/soap-envelope。你知道吗

{S}Envelope中的S替换为上面设置的值将为您提供在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:Success

或者

您还可以使用以下方法直接查找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:Success

相关问题 更多 >