尝试在Python中解析XML响应

2024-09-27 21:24:34 发布

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

我试图从这个XML中获取2个元素(Result和AuthenticationKey)的值。<s:Envelope>语法让我不知所措。在

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
   <s:Body>
      <AuthenticateResponse xmlns="http://remote.Services">
         <AuthenticateResult xmlns:a="http://schemas.datacontract.org/2004/07/remote.Services.Api.DataContracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
            <AdditionalInfo i:nil="true"/>
            <ErrorMessage i:nil="true"/>
            <ErrorMessageId i:nil="true"/>
            <ErrorMessages i:nil="true" xmlns:b="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/>
            <InternalId>0</InternalId>
            <RecordsAffected>0</RecordsAffected>
            <Result>true</Result>
            <WarningMessages i:nil="true" xmlns:b="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/>
            <a:AuthenticationKey>SUPERSECRETTOKEN</a:AuthenticationKey>
            <a:UserGrpId>YYY</a:UserGrpId>
            <a:UserId>XXX</a:UserId>
         </AuthenticateResult>
      </AuthenticateResponse>
   </s:Body>
</s:Envelope>

下面是返回None的相关代码行。两行代码都返回一个None。在

我试图使用stackoverflow的另一个问题中的代码,但是我不确定如何在find方法中为这个特定的xml引入名称空间。在

^{pr2}$

Tags: 代码orgtruehttpremotebodyresultschemas
1条回答
网友
1楼 · 发布于 2024-09-27 21:24:34

xmlns部分成为tags的前缀,也就是说,要找到AuthenticateResponse,您需要搜索{}。在

print(list(tree)[0].find('{http://remote.Services}AuthenticateResponse'))
>>> <Element '{http://remote.Services}AuthenticateResponse' at 0x00000000027228B8>

要获得更一般的解决方案,请看答案here。在

^{pr2}$

相关问题 更多 >

    热门问题