How to add HtmlGenericControl to a HtmlNode?

c# html html-agility-pack htmlgenericcontrol

Question

I'm stuck, this must be very simple to accomplish but i'm not seeing how.

I have this code:

 var divEl = doc.DocumentNode.SelectSingleNode("//div[@id='" + field.Id + "']");

 var newdiv = new HtmlGenericControl("div");
 newdiv.Attributes.Add("id", label.ID);
 newdiv.Attributes.Add("text", label.Text);
 newdiv.Attributes.Add("class", label.CssClass);

And i need to do something like this:

    divEl.AppendChild(newdiv); //not working its expecting a HtmlNode, not a HtmlGenericControl

How can i convert this?

Thanks for any response in advance, chapas

Accepted Answer

Try the code below. you will need to make some changes. controls innerHTML is well formed and can be used as innerXML for an xmlNode

XmlDocument doc = new XmlDocument();
//Load your xml here TODO
var divEl = doc.DocumentElement.SelectSingleNode("//div[@id='test']"); //Change your xpath here TODO
var newdiv = new HtmlGenericControl("div"); 
newdiv.Attributes.Add("id", "id"); 
newdiv.Attributes.Add("text", "text"); 
newdiv.Attributes.Add("class", "class");

XmlNode newNode = doc.CreateNode("NodeType", "NodeName", "URI/if/any"); //update your variables here
newNode.InnerXml = newdiv.InnerHtml;
divEl.AppendChild(newNode);

Hope this helps


Popular Answer

Why not just create the node using HAP's API instead? It should work very similarly.

var newDiv = HtmlNode.CreateNode("<div/>");
newDiv.Attributes.Add("id", label.ID);
newDiv.Attributes.Add("text", label.Text);
newDiv.Attributes.Add("class", label.CssClass);

divEl.AppendChild(newDiv);

There is no easy way to get the outer HTML of the HtmlGenericControl instance (AFAIK). If you had it, you could just pass the HTML in to the HtmlNode.CreateNode() method to create it. But I would strongly suggest not trying to make that work.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why