HtmlAgilityPack 替换节点
我想用新节点替换一个节点。如何获得节点的准确位置并进行完全替换?
我已尝试以下操作,但我无法弄清楚如何获取节点的索引或在哪个父节点上调用 ReplaceChild()
。
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( )
}
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 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( )
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要创建新节点,请使用
HtmlNode.CreateNode()
工厂方法,不要直接使用构造函数。这段代码应该适合您:
请注意,我们需要在查询上调用
ToList()
,我们将修改文档,因此如果不这样做就会失败。如果你想用这个字符串替换:
问题是它不再是单个节点而是一系列节点。您可以使用
HtmlNode.CreateNode()
很好地解析它,但最终,您仅引用序列的第一个节点。您需要使用父节点进行替换。To create a new node, use the
HtmlNode.CreateNode()
factory method, do not use the constructor directly.This code should work out for you:
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:
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.已实施以下解决方案以实现相同的目标。
因此,选择一个对象并删除相应的 HTML 对象
并将其附加为 chile。各自的对象。
Have Implemented the following solution to achieve the same.
so selecting an object and removing respective HTML object
and appending it as chile. of respective object.