Question

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?

Was it helpful?

Solution

HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(@webHTMLeditor.TextXhtml);
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];
    try
    {
        td[0] = cellRows[0];
        td[1] = cellRows[1];
    }
    catch (Exception)
    { }
    //etc   
}

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!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top