Nick
Nick

Reputation: 5696

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

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

Upvotes: 12

Views: 10633

Answers (1)

Hans Kesting
Hans Kesting

Reputation: 39338

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

Upvotes: 20

Related Questions