Search code examples
c#htmlhtml-agility-packhtmlgenericcontrol

How to add HtmlGenericControl to a HtmlNode?


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


Solution

  • 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