【问题标题】:python to pars xml to get valuepython解析xml获取值
【发布时间】:2019-07-11 19:25:40
【问题描述】:

我有一个来自我的系统的 xml 响应,我正在尝试使用 python 代码获取值。需要专家观点突出我的错误。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><ns3:loginResponse xmlns:ns2="http://ws.core.product.xxxxx.com/groupService/" xmlns:ns3="http://ws.core.product.xxxxx.com/loginService/" xmlns:ns4="http://ws.core.product.xxxxx.com/userService/"><ns3:return>YWeVDwuZwHdxxxxxxxxxxx_GqLtkNTE.</ns3:return></ns3:loginResponse>

我正在使用以下代码,但未能获得价值 - YWeVDwuZwHdxxxxxxxxxxx_GqLtkNTE 。我没有使用带命名空间的 xml 解析。 response.text 具有上述 xml 响应。

responsetree = ET.ElementTree(ET.fromstring(response.text))
   responseroot = responsetree.getroot()
   for a in root.iter('return'):
       print(a.attrib)

【问题讨论】:

    标签: python xml xml-namespaces elementtree


    【解决方案1】:

    YWeVDwuZwHdxxxxxxxxxxx_GqLtkNTE 不在attrib 中。它是元素text

    本例中的属性是一个空字典

    请参阅https://www.cmi.ac.in/~madhavan/courses/prog2-2012/docs/diveintopython3/xml.html 关于使用命名空间解析 XML dics。

    【讨论】:

      【解决方案2】:

      其他答案的参考有助于理解这些概念。

      一旦我了解了 xml 结构,它就很简单了。只需添加输出,它可能会帮助将来的人快速参考。

      responsetree = ET.ElementTree(ET.fromstring(response.text)) responseroot = responsetree.getroot() root[0].text

      保持简单易懂。您可能需要找到len(root) 和/或使用条件迭代循环以获得合适的值。您也可以使用findallfind 来获取感兴趣的项目。

      【讨论】:

        猜你喜欢
        • 2018-04-05
        • 2012-09-10
        • 2012-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-28
        • 2012-12-13
        • 1970-01-01
        相关资源
        最近更新 更多