[英]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";
}
因為我需要課堂的價值。 決定我要使用哪個標簽
請檢查以下代碼,您需要通過調用保存方法doc.Save(yourfilepath)
來設置InnerHtml
並保存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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.