[英]Parsing a XML in Python using ElementTree with repeat elements
[英]Parsing XML elements with Python and 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>
我正在嘗試在[CDATA [helpme]]元素內訪問DEALID#(123456789)以及HELPME。 任何幫助是極大的贊賞。 謝謝!
我強烈建議您查看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語法的示例用法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.