Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath - how do you select the child elements of a node?

Tags:

c#

xpath

I have an XmlDocument containing a XHTML table. I'd like to loop through it to process the table cells one row at a time, but the code below is returning all the cells in the nested loop instead of just those for the current row:

XmlNodeList tableRows = xdoc.SelectNodes("//tr");
foreach (XmlElement tableRow in tableRows)
{
    XmlNodeList tableCells = tableRow.SelectNodes("//td");
    foreach (XmlElement tableCell in tableCells)
    {
        // this loops through all the table cells in the XmlDocument,
        // instead of just the table cells in the current row
    }
}

What am I doing wrong? Thanks

like image 219
Nick Avatar asked Jun 15 '11 14:06

Nick


People also ask

How can we find children in XPath?

We can locate child nodes of web elements with Selenium webdriver. First of all we need to identify the parent element with help of any of the locators like id, class, name, xpath or css. Then we have to identify the children with the findElements(By. xpath()) method.

How do you select the first child in XPath?

You have to select the parents first, then use a [#] predicate tag, then select all first children. //div[@class='row spacing-none']/div[1]//a[1] is the XPath you need to select the first a tag link on the whole page.

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.


1 Answers

Start the inner path with a "." to signal that you want to start at the current node. A starting "/" always searches from the root of the xml document, even if you specify it on a subnode.

So:

XmlNodeList tableCells = tableRow.SelectNodes(".//td");

or even

XmlNodeList tableCells = tableRow.SelectNodes("./td");

as those <td>s probably are directly under that <tr>.

like image 119
Hans Kesting Avatar answered Oct 17 '22 21:10

Hans Kesting