MTplus
MTplus

Reputation: 2391

Select single table row using HtmlAgilityPack and iterate its links

I try to iterate a single table row and its a href links but it does not work as expected, instead of finding the selected row and its links it find all links in the table.. What am I doing wrong?

                        var allRows = doc.DocumentNode.SelectNodes("//table[@id='sortingTable']/tr");

        var i = 0;
        var rowNumber = 0;
        foreach (var row in allRows)
        {
            if (row.InnerText.Contains("Text in cell for which row I want to use"))
            {
                rowNumber = i+1;
                break;
            }
            i += 1;
        }

        var list = new List<SortFile>();
        var rowToRead = allRows[rowNumber]; // One specific row

        var numberOfLinks = rowToRead.SelectNodes("//a[@href]"); // this does not find the 2 links in the table row but all links in the whole table?

        foreach (HtmlNode link in rowToRead.SelectNodes("//a[@href]"))
        {
            //HtmlAttribute att = link.Attributes["href"];
            //var text = link.OuterHtml;
        }

Upvotes: 0

Views: 98

Answers (1)

Developer Guy
Developer Guy

Reputation: 2434

The XPath you are using (//a[@href]) would get all of the links in the document. // means to find anything starting from the document root.

You should use .//a[@href] to start from the current node and select all links. That would only take the links underneath the tr node you have selected.

Upvotes: 2

Related Questions