Html Agility Pack - Remove element, but not innerHtml

后端 未结 10 1976
予麋鹿
予麋鹿 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:51

    There is a problem with the bool KeepGrandChildren implementation for people that might have text withing the element they are trying to remove. If the removeme tag had text in it, the text will be removed also. For example text

    more text

    will become

    more text

    Try this:

    private static void RemoveElementKeepText(HtmlNode node)
        {
            //node.ParentNode.RemoveChild(node, true);
            HtmlNode parent = node.ParentNode;
            HtmlNode prev = node.PreviousSibling;
            HtmlNode next = node.NextSibling;
    
            foreach (HtmlNode child in node.ChildNodes)
            {
                if (prev != null)
                    parent.InsertAfter(child, prev);
                else if (next != null)
                    parent.InsertBefore(child, next);
                else
                    parent.AppendChild(child);
    
            }
            node.Remove();
        }
    

提交回复
热议问题