The HTMLAgilityPack ChildNodes index is functional, but the named node is not.

html-agility-pack selectsinglenode


I am parsing an XML API response with HTMLAgilityPack. I am able to select the result items from the API call. Then I loop through the items and want to write the ChildNodes to a table. When I select ChildNodes by saying something like:

sItemId = dnItem.ChildNodes(0).innertext

I get the proper itemId result. But when I try:

sItemId = dnItem.ChildNodes("itemId").innertext

I get "Referenced object has a value of 'Nothing'."

I have tried "itemID[1]", "/itemId[1]" and a veriety of strings. I have tried SelectSingleNode and ChildNodes.Item("itemId").innertext. The only one that has worked is using the index.

The problem with using the index is that sometimes child elements are omitted in the results and that throw off the index.

Anybody know what I am doing wrong?

3/11/2010 7:31:16 PM

Accepted Answer

HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlDocument();
HtmlNodeCollection tableRows = htmlDoc.DocumentNode.SelectNodes("//tr");
for (int i = 0; i < tableRows.Count; i++)
    HtmlNode tr = tableRows[i];

    HtmlNode[] td = new HtmlNode[2];
    string xpath = tr.XPath + "//td";
    HtmlNodeCollection cellRows = tr.SelectNodes(@xpath);
    //td[0] = tr.ChildNodes[1];                
    //td[1] = tr.ChildNodes[3];
        td[0] = cellRows[0];
        td[1] = cellRows[1];
    catch (Exception)
    { }

The code is used to extract data from a table, row by row, by cell per row. I used the existing xpath and I altered it acording to my needs. Good luck!

3/12/2010 3:32:31 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow