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

前端 未结 2 1617
别那么骄傲
别那么骄傲 2021-02-20 03:03

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() metho

2条回答
  •  后悔当初
    2021-02-20 03:44

    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;
    }
    

提交回复
热议问题