Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

HtmlAgilityPack throws stackoverflow exception when calling OuterHtml

var doc = new HtmlDocument();
var table = HtmlNode.CreateNode("table");
var tbody = HtmlNode.CreateNode("tbody");
table.AppendChild(tbody);
doc.DocumentNode.AppendChild(table);
var s = doc.DocumentNode.OuterHtml; //exception is thrown

I am unsure why this throws an exception. I have created 2 nodes and appended the child (tbody) to the parent (table).

In my mind, this should return

<table><tbody></tbody></table>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m not sure what I’ve done wrong

>Solution :

That HtmlNode.CreateNode expects an HTML structure instead of an element name.

From the method definition:

// Creates an HTML node from a string representing literal HTML.
//
// Parameters:
//   html:
//     The HTML text.
//
// Returns:
//     The newly created node instance.
public static HtmlNode CreateNode(string html)

You are looking for the CreateElement method on the HtmlDocument instance.

var doc = new HtmlDocument();
var table = doc.CreateElement("table");
var tbody = doc.CreateElement("tbody");
table.AppendChild(tbody);
doc.DocumentNode.AppendChild(table);

In case you do want to go for HtmlNode.CreateNode then pass the corresponding html tags for the table and tbody.

var table = HtmlNode.CreateNode("<table></table");
var tbody = HtmlNode.CreateNode("<tbody></tbody>");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading