Replacing a HTML div InnerText tag using HTML Agility Pack

别来无恙 提交于 2020-02-03 05:10:07

问题


I'm using the HTML Agility Pack to manipulate and edit a HTML document. I want to change the text in the field such as this:

<div id="Div1"><b>Some text here.</b><br></div>

I am looking to update the text within this div to be:

<div id="Div1"><b>Some other text.</b><br></div>

I've tried doing this using the following code, but it doesn't seem to be working because the InnerText property is readonly.

HtmlTextNode hNode = null;
hNode = hDoc.DocumentNode.SelectSingleNode("//div[@id='Div1']") as HtmlTextNode;
hNode.InnerText = "Some other text.";
hDoc.Save("C:\FileName.html");

What am I doing wrong here? As mentioned above, the InnerText is a read only field, although it's written in the documentation that it "gets or sets". Is there an alternate method through which this can be done?


回答1:


The expression is used here: //div[@id='Div1'] selects the div, which is not a HtmlTextNode, so the hNode variable holds null in your example.

The InnerText property is realy read-only, but HtmlTextNode has property Text which could be used to set the necessary value. But before this you should get that text node. This could be easily done with this expression: //div[@id='Div1']//b//text():

hNode = hDoc.DocumentNode
    .SelectSingleNode("//div[@id='Div1']//b//text()") as HtmlTextNode;
hNode.Text = "Some other text.";


来源:https://stackoverflow.com/questions/9093792/replacing-a-html-div-innertext-tag-using-html-agility-pack

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