2

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>

2 Answers 2

5

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 shown 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);
1
  • I tryed, but i received HtmlAgilityPack.InnerText it is Ready Only
    – Fernando.M
    Feb 16, 2012 at 13:23
1

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;
1
  • : 'Unable to cast object of type 'HtmlAgilityPack.HtmlNode' to type 'HtmlAgilityPack.HtmlTextNode'.'
    – Mukus
    Feb 25, 2020 at 2:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.