如何正确解析此 XML? Python - 元素树

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 它只是 returns 一个整数。 144.(我假设这是它在 xml 中找到的次数。)如果我使用 tree.find('clientid') 我得到 []。我还没有尝试遍历数据,因为我什至找不到它。

我想我已经尝试了我能找到和想到的所有其他组合,但我无法解决这个问题。 find()、findall() 等。我的脑袋在桌子上砰的一声疼。

我需要隔离 clientid、名称 overdue/description。

有人可以解释一下我做错了什么或遗漏了什么吗?谢谢你。

您必须提供完整路径:

client_ids = tree.find('items/client/clientid')

或搜索所有匹配项:

client_ids = tree.findall('.//clientid')

获取元素的内容,例如

for client_id in client_ids:
    print client_id.text