2

当我删除包含文本和子节点的节点(带有keepGrandChildren)时,文本将一直推到子节点之后,而不是停留在其原始位置。

例子:

var doc = new HtmlDocument();
doc.LoadHtml(@"
<span id='first'>
    This text comes first.
    <span id='second'>This text comes second.</span>
</span>");

var node = doc.GetElementbyId("first");
node.ParentNode.RemoveChild(node, true);
doc.Save(Console.Out);

我得到的输出是:

    <span id='second'>This text comes second.</span>
        this text comes first.

代替:

    this text comes first.
    <span id='second'>This text comes second.</span>


有没有什么方法可以在keepGrandChildren不将内部文本推到最后的情况下删除节点?
我想保留绝对顺序并确保没有文本或节点更改其原始位置,否则文档将被破坏。

编辑: 我正在使用HtmlAgilityPack 1.4.6.0.NET 4.0

4

1 回答 1

3

这是 HtmlAgilityPack 中的一个已知问题。下面的代码应该可以解决这个问题:

public static void RemoveChildKeepGrandChildren(HtmlNode parent, HtmlNode oldChild)
{
    if (oldChild.ChildNodes != null)
    {
        HtmlNode previousSibling = oldChild.PreviousSibling;
        foreach (HtmlNode newChild in oldChild.ChildNodes)
        {
            parent.InsertAfter(newChild, previousSibling);
            previousSibling = newChild;  // Missing line in HtmlAgilityPack
        }
    }
    parent.RemoveChild(oldChild);
}
于 2013-01-28T01:15:08.850 回答