Kevin
Kevin

Reputation: 1240

Replacing A Node Using HtmlAgilityPack Throwing Strange Error

I have a webpage that displays a table the user can edit. After the edits are made I want to save the table as a .html file that I can convert to an image later. I am doing this by overriding the render method. However, I want to remove two buttons and a DropDownList from the final version so that I just get the table by itself. Here is the code I am currently trying:

protected override void Render(HtmlTextWriter writer)
{
    using (HtmlTextWriter htmlwriter = new HtmlTextWriter(new StringWriter()))
    {
        base.Render(htmlwriter);
        string renderedContent = htmlwriter.InnerWriter.ToString();
        string output = renderedContent.Replace(@"<input type=""submit"" name=""viewReport"" value=""View Report"" id=""viewReport"" />", "");
        output = output.Replace(@"<input type=""submit"" name=""redoEdits"" value=""Redo Edits"" id=""redoEdits"" />", "");

        var doc = new HtmlDocument();
        doc.LoadHtml(output);

        var query = doc.DocumentNode.Descendants("select");
        foreach (var item in query.ToList())
        {
            var newNodeStr = "<div></div>";
            var newNode = HtmlNode.CreateNode(newNodeStr);
            item.ParentNode.ReplaceChild(newNode, item);
        }

        File.WriteAllText(currDir + "\\outputFile.html", output);

        writer.Write(renderedContent);
    }
}

Where I have adapted this solution found in another SO post about replacing nodes with HtmlAgilityPack:

var htmlStr = "<b>bold_one</b><strong>strong</strong><b>bold_two</b>";
var doc = new HtmlDocument();
doc.LoadHtml(htmlStr);

var query = doc.DocumentNode.Descendants("b");
foreach (var item in query.ToList())
{
    var newNodeStr = "<foo>bar</foo>";
    var newNode = HtmlNode.CreateNode(newNodeStr);
    item.ParentNode.ReplaceChild(newNode, item);
}

and here is the rendered HTML I am trying to alter:

<select name="Archives" onchange="javascript:setTimeout(&#39;__doPostBack(\&#39;Archives\&#39;,\&#39;\&#39;)&#39;, 0)" id="Archives" style="width:200px;">
    <option selected="selected" value="Dashboard_Jul-2012">Dashboard_Jul-2012</option>
    <option value="Dashboard_Jun-2012">Dashboard_Jun-2012</option>
</select>

The two calls to Replace are working as expected and removing the buttons. However this line:

var query = doc.DocumentNode.Descendants("select");

is throwing this error:

Method not found: 'Int32 System.Environment.get_CurrentManagedThreadId()'.

Any advice is appreciated.

Regards.

Upvotes: 3

Views: 2242

Answers (1)

shriek
shriek

Reputation: 5197

Seems like you are using the .Net 4.5 Version of the Agility Pack in a project targeting .Net or lower, you just have to either change the reference of the Dll to the one compiled for your Framework version or change your project to .Net 4.5 (if you're using VS 2012 that is).

Upvotes: 2

Related Questions