【发布时间】:2022-11-16 23:57:08
【问题描述】:
我试图在字符串中找到 H2s,并替换它们以将 id 添加到每个 H2。
var doc = new HtmlDocument();
doc.LoadHtml(blogsContent);
foreach (var node in doc.DocumentNode.SelectNodes("//h2"))
{
var testing = node.OuterHtml.Replace("<h2>", "<h2 id=\"" + node.InnerText + "\">");
// This does the job and changes the <h2> to a <h2 id="..."
}
var html = doc.DocumentNode.OuterHtml;
// However, here, the whole document after the foreach does not include any of the replacements.
我如何让var html 拥有foreach 应该实施的所有更改?
我查看了 StackOverflow,并没有真正找到可以解决我的问题的相同问题。如果我愚蠢,我深表歉意。
【问题讨论】:
-
您构建了
testingvar 但您没有将其设置回节点内容。那就是说,你为什么不node.SetAttributeValue("Id",node.InnerText)? HtmlAgilityPack 的全部目的是避免操作字符串 -
哦,@SteveB。我爱你。
标签: c# html-agility-pack