只返回xpath中元素的文本(python/lxml)

2024-09-29 01:21:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个XML结构:

mytree = """
<path>
    <to>
        <nodes>
            <info>1</info>
            <info>2</info>
            <info>3</info>
        </nodes>
    </to>
</path>
"""

我目前正在python lxml中使用xpath获取节点:

>>> from lxml import etree   
>>> info = etree.XML(mytree)   
>>> print info.xpath("/path/to/nodes/info")
[<Element info at 0x15af620>, <Element info at 0x15af940>, <Element info at 0x15af850>]  
>>> for x in info.xpath("/path/to/nodes/info"):
            print x.text

1
2
3

这很好,但是有没有一种更干净的方法可以将内部文本作为一个列表获取,而不必在之后编写for循环呢?
类似于:

print info.xpath("/path/to/nodes/info/text")

(但那不起作用)


Tags: topathtextinfoforxmlelement结构