HtmlAgilityPack替换节点 [英] HtmlAgilityPack replace node

查看:129
本文介绍了HtmlAgilityPack替换节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一个新节点替换一个节点。我如何获得节点的确切位置并进行完全替换?

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?

我尝试了以下操作,但我不知道如何获取索引节点或哪个父节点调用 ReplaceChild()

I've tried the following, but I can't figured out how to get the index of the node or which parent node to call ReplaceChild() on.

string html = "<b>bold_one</b><strong>strong</strong><b>bold_two</b>";
HtmlDocument document = new HtmlDocument();
document.LoadHtml(html);

var bolds = document.DocumentNode.Descendants().Where(item => item.Name == "b");

foreach (var item in bolds)
{

    string newNodeHtml = GenerateNewNodeHtml();
    HtmlNode newNode = new HtmlNode(HtmlNodeType.Text, document, ?);
    item.ParentNode.ReplaceChild( )
}


推荐答案

要创建新节点,请使用 HtmlNode.CreateNode()工厂方法,请勿直接使用构造函数。

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

此代码应该为您解决:

var htmlStr = "<b>bold_one</b><strong>strong</strong><b>bold_two</b>";
var doc = new HtmlDocument();
doc.LoadHtml(htmlStr);

var query = doc.DocumentNode.Descendants("b");
foreach (var item in query.ToList())
{
    var newNodeStr = "<foo>bar</foo>";
    var newNode = HtmlNode.CreateNode(newNodeStr);
    item.ParentNode.ReplaceChild(newNode, item);
}

请注意,我们需要调用 ToList()在查询中,我们将对文档进行修改,因此如果不这样做,将失败。

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 <b>node</b> <strong>another node</strong>"

问题是它不再是单个节点,而是一系列节点。您可以使用 HtmlNode.CreateNode()对其进行解析,但最后,您仅引用序列的第一个节点。您需要使用父节点进行替换。

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 = "<b>bold_one</b><strong>strong</strong><b>bold_two</b>";
var doc = new HtmlDocument();
doc.LoadHtml(htmlStr);

var query = doc.DocumentNode.Descendants("b");
foreach (var item in query.ToList())
{
    var newNodesStr = "some text <b>node</b> <strong>another node</strong>";
    var newHeadNode = HtmlNode.CreateNode(newNodesStr);
    item.ParentNode.ReplaceChild(newHeadNode.ParentNode, item);
}

这篇关于HtmlAgilityPack替换节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆