如何根据XPath获取所有元素?

后端开发 2026-07-12

如何用lxml的 XPATH获取所有Points元素?

xml = etree.parse(args.file).getroot()
el = xml.find(".//cims:Period", tools.namespaces)
log.info(f"number of elements under Period:{len(el)}") # correct
log.info(etree.tostring(el, pretty_print=True).decode())
el = el.find(".//cims:Point", tools.namespaces)
log.info(f"number of elements in Point:{len(el)}") # should this not be 96?
log.info(etree.tostring(el, pretty_print=True).decode())
number of elements under Period:98
<Period xmlns="urn:iec62325.351:tc57wg16:451-2:scheduledocument:5:0" xmlns:env="http://www.w3.org/2003/05/soap-envelope">
                    <timeInterval>
                        <start>2026-02-16T23:00Z</start>
                        <end>2026-02-17T23:00Z</end>
                    </timeInterval>
                    <resolution>PT15M</resolution>
                    <Point>
                        <position>1</position>
                        <quantity>0.0</quantity>
                    </Point>
:
                    <Point>
                        <position>96</position>
                        <quantity>13.0</quantity>
                    </Point>
                </Period>

为什么只有一个,难道不会返回一个长度为96的数组吗?

number of elements in Point:2
<Point xmlns="urn:iec62325.351:tc57wg16:451-2:scheduledocument:5:0" xmlns:env="http://www.w3.org/2003/05/soap-envelope">
                        <position>1</position>
                        <quantity>0.0</quantity>
                    </Point>

解决方案

参考:https://lxml.de/tutorial.html

  • iterfind():遍历所有与路径表达式匹配的元素
  • findall():返回匹配元素的列表
  • find():高效地返回第一个匹配项
  • findtext():返回第一个匹配项的.text内容

find() 仅会找到第一个匹配项,请改用findall()。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章