HtmlAgilityPack set node InnerText

回眸只為那壹抹淺笑 提交于 2019-12-04 15:16:52

问题


I want to replace inner text of HTML tags with another text. I am using HtmlAgilityPack
I use this code to extract all texts

HtmlDocument doc = new HtmlDocument();
doc.Load("some path")

foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//text()[normalize-space(.) != '']")) {
    // How to replace node.InnerText with some text ?
}

But InnerText is readonly. How can I replace texts with another text and save them to file ?


回答1:


Try code below. It select all nodes without children and filtered out script nodes. Maybe you need to add some additional filtering. In addition to your XPath expression this one also looking for leaf nodes and filter out text content of <script> tags.

var nodes = doc.DocumentNode.SelectNodes("//body//text()[(normalize-space(.) != '') and not(parent::script) and not(*)]");
foreach (HtmlNode htmlNode in nodes)
{
    htmlNode.ParentNode.ReplaceChild(HtmlTextNode.CreateNode(htmlNode.InnerText + "_translated"), htmlNode);
}



回答2:


Strange, but I found that InnerHtml isn't readonly. And when I tried to set it like that

aElement.InnerHtml = "sometext";

the value of InnerText also changed to "sometext"



来源:https://stackoverflow.com/questions/8274421/htmlagilitypack-set-node-innertext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!