首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何解析包含python中带有xml命名空间标记的节点的xml数据?

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

Stack Overflow用户
提问于 2019-10-31 11:13:57
回答 1查看 113关注 0票数 2

我得到XML作为响应,所以我想解析它。我尝试了许多python库,但没有得到我想要的结果。所以如果你能帮忙的话,它会很感激的。

以下代码返回None

代码语言:javascript
复制
xmlResponse = ET.fromstring(context.response_document)
a = xmlResponse.findall('.//Body')
print(a)

示例XML数据:

代码语言:javascript
复制
<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>

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-31 21:04:18

给定以下基本代码:

代码语言:javascript
复制
import xml.etree.ElementTree as ET

root = ET.fromstring(xml)

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

.//Body x路径的初始查找不返回任何结果,因为它不存在于您的XML响应中。

XML中的每个标记都有一个与其关联的命名空间。有关xml名称空间的更多信息可以找到这里

考虑使用xmlns值(xml-命名空间)的以下行:

代码语言:javascript
复制
<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中找到的结果标记:

代码语言:javascript
复制
root.find('{http://www.w3.org/2003/05/soap-envelope}Envelope') #top most node

我们也需要为<S:Body>做同样的事情。

要获取<S:Body>元素及其子节点,可以执行以下操作:

代码语言:javascript
复制
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

产出:

代码语言:javascript
复制
{urn:oasis:names:tc:ebxml-regrep:xsd:query:3.0}AdhocQueryResponse
urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Success

Alternatively

您还可以使用以下方法直接查找XML中的所有 {query}AdhocQueryResponse

代码语言:javascript
复制
response_nodes = root.findall('.//{urn:oasis:names:tc:ebxml-regrep:xsd:query:3.0}AdhocQueryResponse')

for response in response_nodes:
  print(response.get('status'))

产出:

代码语言:javascript
复制
urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Success
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58642152

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档