Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html Agility Pack/C#: how to create/replace tags?

Tags:

html

c#

parsing

The task is simple, but I couldn't find the answer.

Removing tags (nodes) is easy with Node.Remove()... But how to replace them?

There's a ReplaceChild() method, but it requires to create a new tag. How do I set the contents of a tag? InnerHtml and OuterHtml are read only properties.

like image 464
Alex Avatar asked Jun 30 '11 19:06

Alex


1 Answers

See this code snippet:

public string ReplaceTextBoxByLabel(string htmlContent) 
{
  HtmlDocument doc = new HtmlDocument();
  doc.LoadHtml(htmlContent);

  foreach(HtmlNode tb in doc.DocumentNode.SelectNodes("//input[@type='text']"))
  {
    string value = tb.Attributes.Contains("value") ? tb.Attributes["value"].Value : " ";
    HtmlNode lbl = doc.CreateElement("span");
    lbl.InnerHtml = value;

    tb.ParentNode.ReplaceChild(lbl, tb);
  }

  return doc.DocumentNode.OuterHtml;
}
like image 87
Pavel Hodek Avatar answered Sep 20 '22 11:09

Pavel Hodek