Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xpath to get all the childrens text

Tags:

xpath

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.

like image 677
pallavi Avatar asked May 02 '12 12:05

pallavi


People also ask

How do I select all child elements in XPath?

For the div element with an id attribute of hero //div[@id='hero'] , these XPath expression will select elements as follows: //div[@id='hero']/* will select all of its children elements. //div[@id='hero']/img will select all of its children img elements. //div[@id='hero']//* will select all of its descendent elements.

What is child :: In XPath?

As defined in the W3 XPath 1.0 Spec, " child::node() selects all the children of the context node, whatever their node type." This means that any element, text-node, comment-node and processing-instruction node children are selected by this node-test.

How do I select text in XPath?

Do note that /html/text() doesn't select all text nodes in the document -- only the text nodes that are children (not descendents) of the top, html element. You probably want /html//text() . Some knowledge and understanding of XPath is typically required in order to construct XPath expressions.


2 Answers

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

//ul/descendant::*/text() 
like image 145
erikxiv Avatar answered Nov 12 '22 19:11

erikxiv


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() 
like image 43
igo Avatar answered Nov 12 '22 18:11

igo