【问题标题】:Parsing XML elements with Python and Elementtree使用 Python 和 Elementtree 解析 XML 元素
【发布时间】:2018-08-27 10:46:39
【问题描述】:

我是一个尝试使用 Elementtree 解析 XML API 响应的 Python 菜鸟。响应包含来自表单的自定义数据,我在尝试访问某些嵌套元素时遇到了麻烦。以下是我的代码:

response = requests.get("https://crm.zoho.com/crm/private/xml/Deals/getCVRecords?newFormat=1&authtoken=authtoken&scope=crmapi&cvName=Open Deals")
tree = ElementTree.fromstring(response.content)
print (response.text)

通过这个电话,我能够得到这样的回应:

<?xml version="1.0" encoding="UTF-8" ?>
<response uri="/crm/private/xml/Deals/getCVRecords">
<result>
    <Deals>
        <row no="1">
            <FL val="DEALID">123456789</FL>
            <FL val="SMOWNERID">0000000000</FL>
            <FL val="Deal Owner"><![CDATA[helpme]]></FL>
        </row>
    </Deals>
</result>
</response>

我正在尝试访问 [CDATA[helpme]] 元素中的 DEALID# (123456789) 以及 HELPME。任何帮助是极大的赞赏。谢谢!

【问题讨论】:

  • 你试过什么?你知道在tree.find 中使用 XPATH 查询吗?
  • 如果您对 XPATH 感到困惑,.//FL[@val='DEALID'] 会处理您的第一个问题,或者./result/Deals/row/FL[@val='DEALID']。您应该能够决定是想要第一个,第二个,还是比第一个更明确但不如第二个明确的东西。从那里开始,弄清楚如何从节点中取出文本,以及如何进行其他搜索,应该很容易。但是,如果您遇到困难,您将有一个很好的、具体的问题要问。

标签: python xml xml-parsing elementtree


【解决方案1】:

我强烈建议您查看https://github.com/martinblech/xmltodict。我已经将它用于大量 XML 处理,它非常可靠。

>>> xml = """
... <root xmlns="http://defaultns.com/"
...       xmlns:a="http://a.com/"
...       xmlns:b="http://b.com/">
...   <x>1</x>
...   <a:y>2</a:y>
...   <b:z>3</b:z>
... </root>
... """
>>> xmltodict.parse(xml, process_namespaces=True) == {
...     'http://defaultns.com/:root': {
...         'http://defaultns.com/:x': '1',
...         'http://a.com/:y': '2',
...         'http://b.com/:z': '3',
...     }
... }
True

【讨论】:

    【解决方案2】:

    下面的代码应该找到并打印出它找到的每个交易 ID。

    import xml.etree.ElementTree as ET
    import requests
    
    root = ET.fromstring(requests.get(your_link).content)
    
    # find 'result' element
    result = root.find('result')
    # then, find 'Deals' which was nested in 'result'
    deals = result.find('Deals')
    
    # this can be simplified:
    deals = root.find('result').find('Deals')
    
    for row in deals.findall('row'):  # go through all rows (I assumed there can be more than one)
        deal_id_elem = row.find('FL[@val="DEALID"]')
        print('Found ID', deal_id_elem.text)
    

    deal_id_elem = row.find('FL[@val="DEALID"]') 查找属性val 等于DEALID 的元素。这是使用的示例 Xpath syntax

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-16
      • 1970-01-01
      • 2012-02-07
      • 2021-02-06
      • 2017-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多