pdf to image pdf to image -4 years ago 167
C# Question

Add element to html using htmlagilitypack

How do i insert another tag after a specific tag, and remove a tag

example i have this html

<p class="cs40314EBF"><span class="cs1B16EEB5">This is an ordinary text.</span></p>


and this is the possible output

<p class="cs40314EBF"><b>This is an ordinary text.</b></p>


this is my code

HtmlDocument doc = new HtmlDocument();
doc.Load(htmlLocation);
foreach (var item in doc.DocumentNode.Descendants())
{

if (item.Name == "span")
{
HtmlNode div = doc.CreateElement("b");
//what do i need to do here?
}
}


i did a research and found this

http://www.nudoq.org/#!/Packages/HtmlAgilityPack/HtmlAgilityPack/HtmlNode/M/InsertBefore


but i can't make it work.

i can't use

if (item.Name == "span")
{

item.Name = "newtag";
}


because i need the value of the class. to decide which tag am i going to use

Answer Source

Please check the below code, you need to set InnerHtml and save Html document by calling save method doc.Save(yourfilepath).

            if (item.Name == "span")
            {

                HtmlNode div = doc.CreateElement("b");
                div.InnerHtml = "Hello world";
                item.AppendChild(div);
                doc.Save(yourfilepath);
            }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download