xpath to get all the childrens text

29,871

Solution 1

This will retrieve all text elements with a parent ul element.

//ul/descendant::*/text()

Solution 2

You can use XPath axis. An axis represents a relationship to the context node, and is used to locate nodes relative to that node on the tree. As of today there are 13 axes. You can use descendant for all of the children (including nested) of the context node or descendant-or-self axis which indicates the context node and all of its descendants. For example:

//ul/descendant::*/text()
//ul/descendant-or-self::*/text()
Share:
29,871
pallavi
Author by

pallavi

Updated on July 09, 2022

Comments

  • pallavi
    pallavi almost 2 years

    Is there any way to get all the childrens node values within the ul tag.

    Input:

    <ul>
        <li class="type">Industry</li> 
    
        <li><a href="/store/Browse/?N=355+361+4294855087">Automotive</a></li>                            
    
        <li><a href="/store/Browse/?N=355+361+4294855065">Parts </a></li>                                
    
        <li>Tires</li>                  
    </ul>
    

    Output: Industry, Automotive, Parts, Tires.

  • djangofan
    djangofan over 10 years
    Tried this and it wouldn't work: /a[not(contains(descendant::*/text(),'Networks'))]
  • bman
    bman about 8 years
    More accurate answer is to use descendant-or-self to get the text of the element itself, if the element does not have any children.