Html Agility Pack - Remove element, but not innerHtml

后端 未结 10 2073
予麋鹿
予麋鹿 2021-01-06 11:46

I can easily remove the element just by note.Remove() lik this:

HtmlDocument html = new HtmlDocument();

html.Load(Server.MapPath(@\"~\\Site\\themes\\default         


        
10条回答
  •  鱼传尺愫
    2021-01-06 11:49

    This should work:

    foreach (var item in doc.DocumentNode.SelectNodes("//removeMe"))
    {
        if (item.PreviousSibling == null)
        {
            //First element -> so add it at beginning of the parent's innerhtml
            item.ParentNode.InnerHtml = item.InnerHtml + item.ParentNode.InnerHtml;
        }
        else
        {
            //There is an element before itemToRemove -> add the innerhtml after the previous item
            foreach(HtmlNode node in item.ChildNodes){
                item.PreviousSibling.ParentNode.InsertAfter(node, item.PreviousSibling);
            }
        }
        item.Remove();
    }
    

提交回复
热议问题