试图在Python中解析XML响应

时间:2017-05-02 13:23:35

标签: python xml elementtree

我正在尝试从此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上使用另一个问题的代码,但我不确定如何在这个特定的xml的find方法中引入名称空间。

tree = ElementTree.fromstring(resp.text)
    token = tree.find("AuthenticateResponse") #Option1
    token = tree.find("Envelope/Body/AuthenticateResponse/AuthenticateResult/AuthenticationKey") #Option2
    print token

1 个答案:

答案 0 :(得分:0)

static public Data loadData() { Data database = new Data(); myConnexion.Open(); /// <summary> /// Loading of the categories /// </summary> MySqlCommand command = new MySqlCommand("getCategory", myConnexion); command.CommandType = System.Data.CommandType.StoredProcedure; using (var cursor = command.ExecuteReader()) { while (cursor.Read()) { int id = Convert.ToInt32(cursor["id"]); string categoryName = Convert.ToString(cursor["name"]); Category category = new Category(id, categoryName); database.addCategory(category); } } /// <summary> /// Loading of the projects /// </summary> command = new MySqlCommand("getProject", myConnexion); command.CommandType = System.Data.CommandType.StoredProcedure; using(var cursor = command.ExecuteReader()) { while (cursor.Read()) { int idProject = Convert.ToInt32(cursor["id"]); string name = Convert.ToString(cursor["name"]); int idCategory = Convert.ToInt32(cursor["idCategory"]); Category category = database.getCategories()[idCategory]; Project project = new Project(idProject, name, category); Link.addProject(project.getName(), category); } } myConnexion.Close(); return database; } 部分成为xmlns的前缀,即找到您需要搜索tags的{​​{1}}。

AuthenticateResponse

对于更通用的解决方案,请查看答案here

{http://remote.Services}AuthenticateResponse