【问题标题】:HtmlAgilityPack - Keep text position upon removal of nodeHtmlAgilityPack - 删除节点后保留文本位置
【发布时间】:2013-01-11 07:45:28
【问题描述】:

当我删除包含文本和子节点的节点(使用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

【问题讨论】:

    标签: c# html parsing html-agility-pack


    【解决方案1】:

    它是 HtmlAgilityPack 中的 know issue。下面的代码应该可以解决问题:

    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);
    }
    

    【讨论】:

    • 一个简单的测试确实表明这段代码可以满足我的要求,而且它比我想出的半hacky方式快得多。我会尝试一下,看看效果如何。
    • 更新: 这个解决方案完美而高效。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多