用Python和Elemen解析XML元素

2024-09-29 04:27:49 发布

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

我是一个pythonnoob,试图使用Elementtree解析xmlapi响应。响应包含来自窗体的自定义数据,我在尝试访问某些嵌套元素时遇到问题。以下是我的代码:

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)

通过这个电话,我可以得到以下回复:

^{pr2}$

我试图访问DEALID(123456789)以及[CDATA[HELPME]]元素中的HELPME。非常感谢任何帮助。谢谢!在


Tags: 代码https元素getresponse窗体requestscrm
2条回答

我强烈建议你去看看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

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

相关问题 更多 >