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

Lit*_*les 3 python xml xpath lxml xml-parsing

我有这样的XML结构:

mytree = """
<path>
    <to>
        <nodes>
            <info>1</info>
            <info>2</info>
            <info>3</info>
        </nodes>
    </to>
</path>
"""
Run Code Online (Sandbox Code Playgroud)

我目前正在使用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
Run Code Online (Sandbox Code Playgroud)

这是伟大的,但有没有抢到一个更清洁的方式只是内部的文本作为一个列表,而不是在事后写for循环?
就像是:

print info.xpath("/path/to/nodes/info/text")
Run Code Online (Sandbox Code Playgroud)

(但这不起作用)

kev*_*kev 9

您可以使用:

print info.xpath("/path/to/nodes/info/text()")
Run Code Online (Sandbox Code Playgroud)