[英]How do I correctly parse this XML? Python - ElementTree
我在解析此XML时遇到问题。 我是python的新手,所以我可能不了解一个概念,或者我可能错过了一步。
XML块:
<result created="2015-12-05T12:46:00-06:00" host="www.systemmonitor.us" status="OK">
<items>
<client>
<clientid>67300</clientid>
<name>
<![CDATA[ ACME Company ]]>
</name>
<site>
<siteid>85663</siteid>
<name>
<![CDATA[ Los Angeles ]]>
</name>
<workstations/>
<servers>
<server>
<id>597207</id>
<name>
<![CDATA[ SERVER1 ]]>
</name>
<offline>
<description>
<![CDATA[ OFFLINE - MAINTENANCE MODE ]]>
</description>
<startdate>2015-11-25</startdate>
<starttime>01:40:07</starttime>
</offline>
</server>
<server>
<id>2252213</id>
<name>
<![CDATA[ SERVER2 ]]>
</name>
<overdue>
<description>
<![CDATA[ Overdue ]]>
</description>
<startdate>2015-11-25</startdate>
<starttime>01:57:40</starttime>
</overdue>
</server>
</servers>
</site>
</client>
我需要提取某些元素,以便可以将这些元素推入我们的CRM系统。
这是我的代码:
import requests
import xml.etree.ElementTree as ET
url = "https://www.systemmonitor.us/api/"
querystring = {"apikey":"SUPERSECRETAPIKEY","service":"list_failing_checks"}
response = requests.request("GET", url, params=querystring)
msg = response.text
tree = ET.ElementTree(ET.fromstring(msg))
client_ids = tree.find('clientid')
print client_ids
如果我尝试从msg.find('clientid')获取client_id,它只会返回一个整数。 144。(我假设这是在xml中找到它的次数。)如果我使用tree.find('clientid'),则得到[]。 我还没有尝试遍历数据,因为似乎无法找到它。
我想我已经尝试过可以找到并想到的所有其他组合,但是无法解决。 find(),findall()等。我的大脑因在桌子上猛击而受伤。
我需要隔离clientid,名称,过期/描述。
有人可以解释我做错了什么或我错过了什么吗? 谢谢。
您必须给出完整的路径:
client_ids = tree.find('items/client/clientid')
或使用以下命令搜索所有事件:
client_ids = tree.findall('.//clientid')
要获取元素的内容,请使用例如
for client_id in client_ids:
print client_id.text
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.