HtmlAgilityPack replace node

前端 未结 2 491
星月不相逢
星月不相逢 2020-12-14 08:04

I want to replace a node with a new node. How can I get the exact position of the node and do a complete replace?

I\'ve tried the following, but I can\'t figured out

2条回答
  •  借酒劲吻你
    2020-12-14 08:40

    To create a new node, use the HtmlNode.CreateNode() factory method, do not use the constructor directly.

    This code should work out for you:

    var htmlStr = "bold_onestrongbold_two";
    var doc = new HtmlDocument();
    doc.LoadHtml(htmlStr);
    
    var query = doc.DocumentNode.Descendants("b");
    foreach (var item in query.ToList())
    {
        var newNodeStr = "bar";
        var newNode = HtmlNode.CreateNode(newNodeStr);
        item.ParentNode.ReplaceChild(newNode, item);
    }
    

    Note that we need to call ToList() on the query, we will be modifying the document so it would fail if we don't.


    If you wish to replace with this string:

    "some text node another node"
    

    The problem is that it is no longer a single node but a series of nodes. You can parse it fine using HtmlNode.CreateNode() but in the end, you're only referencing the first node of the sequence. You would need to replace using the parent node.

    var htmlStr = "bold_onestrongbold_two";
    var doc = new HtmlDocument();
    doc.LoadHtml(htmlStr);
    
    var query = doc.DocumentNode.Descendants("b");
    foreach (var item in query.ToList())
    {
        var newNodesStr = "some text node another node";
        var newHeadNode = HtmlNode.CreateNode(newNodesStr);
        item.ParentNode.ReplaceChild(newHeadNode.ParentNode, item);
    }
    

提交回复
热议问题