Change Tag InnerText with HTML AGILITY PACK

c# html html-agility-pack

Question

Im using HTML Agility Pack, and Im trying to replace the InnerText of some Tags like this

protected void GerarHtml()
{
    List<string> labels = new List<string>();

    string patch = @"C:\EmailsMKT\" + 
                              Convert.ToString(Session["ssnFileName"]) + ".html";

     DocHtml.Load(patch);

     //var titulos = DocHtml.DocumentNode.SelectNodes("//*[@class='lblmkt']");

     foreach (HtmlNode titulo in
              DocHtml.DocumentNode.SelectNodes("//*[@class='lblmkt']"))
     {
          titulo.InnerText.Replace("test", lbltitulo1.Text);
     }

     DocHtml.Save(patch);

}

the html:

<.div><.label id="titulo1" class="lblmkt">teste</label.><./Div>

Accepted Answer

Strings are immutable (you should be able to find much documentation on this).
Methods of the String class do not alter the instance, but rather create a new, modified string.

Thus, your call to:

titulo.InnerText.Replace("test", lbltitulo1.Text);

does not alter InnerText, but returns the string you want InnerText to be.

In addition, InnerText is read-only; you'll have to use Text as seem in Set InnerText with HtmlAgilityPack

Try the following line instead (assign the result of the string operation to the property again):

titulo.Text = titulo.Text.Replace("test", lbltitulo1.Text);

Popular Answer

I was able get the result like this:

HtmlTextNode Hnode = null;
Hnode = DocHtml.DocumentNode.SelectSingleNode("//label[@id='titulo1']//text()") as HtmlTextNode;
Hnode.Text = lbltitulo1.Text;


Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow