Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Just returning the text of elements in xpath (python / lxml)

I have an XML structure like this:

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

I'm currently using xpath in python lxml to grab the nodes:

>>> 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

This is great, but is there a cleaner way to grab just the internal texts as a list, rather than having to write the for-loop afterwards?
Something like:

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

(but that doesn't work)

like image 327
LittleBobbyTables Avatar asked Dec 21 '22 01:12

LittleBobbyTables


1 Answers

You can use:

print info.xpath("/path/to/nodes/info/text()")
like image 77
kev Avatar answered Dec 28 '22 09:12

kev