Html Agility Pack - Remove element, but not innerHtml

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

    Normally the correct expression would be node.ParentNode.RemoveChildren(node, true).

    Due to a ordering bug in HtmlNode.RemoveChildren() (http://htmlagilitypack.codeplex.com/discussions/79587), I have created a method that is similar. Sorry it's in VB. If anyone wants a translation I'll write one.

    'The HTML Agility Pack (1.4.9) includes the HtmlNode.RemoveChild() method but it has an ordering bug with preserving child nodes.  
    'The below implementation orders children correctly.
    Private Shared Sub RemoveNode(node As HtmlAgilityPack.HtmlNode, keepChildren As Boolean)
        Dim parent = node.ParentNode
        If keepChildren Then
            For i = node.ChildNodes.Count - 1 To 0 Step -1
                parent.InsertAfter(node.ChildNodes(i), node)
            Next
        End If
        node.Remove()
    End Sub
    

    I have tested this code with the following test markup:

    
        outertextbegin
        

    innertext1

    innertext2

    outertextend

    The output is:

    outertextbegin
    

    innertext1

    innertext2

    outertextend

提交回复
热议问题