使用 htmlagility pack 将元素添加到 html

Add element to html using htmlagilitypack

如何在特定标签后插入另一个标签,以及删除标签

例子我有这个html

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

这是可能的输出

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

这是我的代码

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?
    }
}

我做了一个调查,发现了这个

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

但我做不到。

我不会用

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

      item.Name = "newtag";
   }

因为我需要 class 的值。决定我要使用哪个标签

请检查以下代码,您需要设置 InnerHtml 并通过调用保存方法 doc.Save(yourfilepath) 保存 Html 文档。

if (item.Name == "span")
{
  HtmlNode div = doc.CreateElement("b");
  div.InnerHtml = "Hello world";
  item.AppendChild(div);
  doc.Save(yourfilepath);
}

你能试试这个吗?

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();
        }
    }