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
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);
}
Can you try this?
var doc1 = new HtmlAgilityPack.HtmlDocument();
doc1.LoadHtml("<p class=\"cs40314EBF\"><span class=\"cs1B16EEB5\">This is an ordinary text.</span></p>");
foreach (var item in doc1.DocumentNode.Descendants())
{
if (item.Name == "span")
{
HtmlNode b = doc.CreateElement("b");
b.InnerHtml = item.InnerText;
item.ParentNode.AppendChild(b);
item.Remove();
}
}