简体   繁体   中英

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)

您可以使用:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM