简体   繁体   中英

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

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.

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

Well there is a way to get your OuterHtml from HtmlGenericControl:

using (TextWriter textWriter = new StringWriter())
{
    using (HtmlTextWriter htmlWriter = new HtmlTextWriter(textWriter))
    {
        HtmlGenericControl control = new HtmlGenericControl("div");

        control.Attributes.Add("One", "1");
        control.Attributes.Add("Two", "2");
        control.InnerText = "Testing 123";

        control.RenderControl(htmlWriter);
    }
}

the textWriter.ToString() will get you following:

<div One="1" Two="2">Testing 123</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM