Tag Replacement in HtmlAgility

I am trying to replace all h1 tags with h2 tags and I am using the HtmlAgility package.

I have done this:

 var headers = doc.DocumentNode.SelectNodes("//h1"); if (headers != null) { foreach (HtmlNode item in headers) { //item.Replace?? } } 

and I'm stuck there. I tried this:

 var headers = doc.DocumentNode.SelectNodes("//h1"); if (headers != null) { foreach (HtmlNode item in headers) { HtmlNode newNode = new HtmlNode(HtmlNodeType.Element, doc, item.StreamPosition); newNode.InnerHtml = item.InnerHtml; // newNode suppose to set to h2 item.ParentNode.ReplaceChild(newNode, item); } } 

the problem is that I have no idea how to create a new h2, get all the attributes, etc. I'm sure this is an easy way to do this, any ideas?

+6
source share
2 answers
 var headers = doc.DocumentNode.SelectNodes("//h1"); if (headers != null) { foreach (HtmlNode item in headers) { item.Name = "h2" } } 
+10
source

A similar approach replacing tags using descendants instead of SelectNodes:

 IEnumerable<HtmlNode> tagDescendants = doc.DocumentNode.Descendants("h1"); foreach (HtmlNode htmlNode in tagDescendants) { htmlNode.Name = "h2"; } 
+1
source

Source: https://habr.com/ru/post/887610/


All Articles