Replacing an InnerText HTML Tag with HTML Agility Pack

I use the HTML Agility Pack to manage and edit an HTML document. I want to change the text in a field, for example:

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

I want to update the text inside this div:

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

I tried to do this using the following code, but it doesn't seem to work because the InnerText property is read-only.

 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, InnerText is a read-only field, although it is written in the documentation that it “receives or installs”. Is there an alternative method by which this can be done?

+6
source share
1 answer

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

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

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

Source: https://habr.com/ru/post/907379/


All Articles