使用 ETree 在 Python 中进行简单 XML 解析

Simple XML Parsing In Python Using ETree

我正在尝试使用最新版本 python 中的 Element Tree 解析此 XML。我想做的是计算 APPINFO 元素的数量,然后从 APPINFO 的最新实例(树中的最后一个)中获取数据。到目前为止,我能够使用

获取 APPINFO 元素的数量
count = len(root.findall("./APPINFO"))

但是我如何只引用树中的最后一个并提取值?

<APPLICANT>
<APPINFO>
    <FIRSTNAME>Joe</FIRSTNAME>
    <LASTNAME>Smith</LASTNAME>
    <MIDDLENAME></MIDDLENAME>
    <OTHERNAME></OTHERNAME>
</APPINFO>
<APPLICANT>
<APPINFO>
    <FIRSTNAME>Peter</FIRSTNAME>
    <LASTNAME>Smith</LASTNAME>
    <MIDDLENAME></MIDDLENAME>
    <OTHERNAME></OTHERNAME>
</APPINFO>
<APPINFO> #I need the data out of this one only
    <FIRSTNAME>John</FIRSTNAME>
    <LASTNAME>Smith</LASTNAME>
    <MIDDLENAME></MIDDLENAME>
    <OTHERNAME></OTHERNAME>
</APPINFO>

计算和访问最后一个元素的工作示例。使用列表时,负索引从列表末尾访问元素。

from xml.etree import ElementTree as et

data = '''\
<APPLICANT>
  <APPINFO>
    <FIRSTNAME>Joe</FIRSTNAME>
    <LASTNAME>Smith</LASTNAME>
    <MIDDLENAME></MIDDLENAME>
    <OTHERNAME></OTHERNAME>
  </APPINFO>
  <APPINFO>
    <FIRSTNAME>Peter</FIRSTNAME>
    <LASTNAME>Smith</LASTNAME>
    <MIDDLENAME></MIDDLENAME>
    <OTHERNAME></OTHERNAME>
  </APPINFO>
  <APPINFO>
    <FIRSTNAME>John</FIRSTNAME>
    <LASTNAME>Smith</LASTNAME>
    <MIDDLENAME></MIDDLENAME>
    <OTHERNAME></OTHERNAME>
  </APPINFO>
</APPLICANT>'''

tree = et.fromstring(data)
appinfo = tree.findall("./APPINFO")
print(len(appinfo))
et.dump(appinfo[-1])
print(appinfo[-1].find('FIRSTNAME').text)

输出:

3
<APPINFO>
    <FIRSTNAME>John</FIRSTNAME>
    <LASTNAME>Smith</LASTNAME>
    <MIDDLENAME />
    <OTHERNAME />
  </APPINFO>
John
allAppInfo=root.findall("./APPINFO")

以上returns个元素列表。

count=len(allAppInfo)

以上returns列表中元素的个数allAppInfo

last=allAppInfo[count-1]

上面的 returns 列表中的最后一个元素是索引 count-1 处的元素。

last=allAppInfo[-1]

上面还有 returns 列表中的最后一个元素,从最后一个开始索引为 -1。