使用Python和Elementtree解析XML元素

时间:2018-03-18 22:21:19

标签: python xml xml-parsing elementtree

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

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>

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

2 个答案:

答案 0 :(得分:0)

我强烈建议您查看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

答案 1 :(得分:0)

下面的代码应该找到并打印出它找到的每个交易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