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

2019-04-05 02:54发布

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.

标签: c# html parsing
2条回答
混吃等死
2楼-- · 2019-04-05 03:50

Are you sure InnerHtml is a read only property?

The HTMLAgility pack's documentation says otherwise: (Cut & Paste)

Gets or Sets the HTML between the start and end tags of the object.

Namespace:  HtmlAgilityPack
Assembly:  HtmlAgilityPack (in HtmlAgilityPack.dll) Version: 1.4.0.0 (1.4.0.0)
Syntax
C# 
public virtual string InnerHtml { get; set; }

If it is read only could you post some code?

查看更多
We Are One
3楼-- · 2019-04-05 03:56

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;
}
查看更多
登录 后发表回答