Home > database >  HtmlAgilityPack throws stackoverflow exception when calling OuterHtml
HtmlAgilityPack throws stackoverflow exception when calling OuterHtml

Time:02-01

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>

I'm not sure what I've done wrong

CodePudding user response:

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>");
  • Related