Skip to main content
 首页 » 编程设计

python之我们如何在 python 中解析包含带有 xml 命名空间标签的节点的 xml 数据

2024年11月01日10artech

我收到 XML 作为响应,所以我想解析它。我尝试了很多 python 库,但没有得到我想要的结果。因此,如果您能提供帮助,我们将不胜感激。

以下代码返回无:

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> 

我想从它的 Body 中获取状态。如果您可以建议对某些库进行一些更改,请帮助我。谢谢

请您参考如下方法:

给定以下基本代码:

import xml.etree.ElementTree as ET 
 
root = ET.fromstring(xml) 

让我们在此基础上构建以获得您想要的输出。

您对 .//Body 的初始查找x-path 返回 NONE 因为它不存在于您的 XML 响应中。

XML 中的每个标记都有一个与之关联的命名空间。可以找到有关 xml namespace 的更多信息 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在 {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:Success 

或者

也可以直接全部 {query}AdhocQueryResponse在您的 XML 中使用:

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