Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing tags in HtmlAgility

I'm trying to replace all of my h1 tags with h2 tags and I'm using HtmlAgility pack.

I did this:

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

and i got stuck there. I've 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);
    }
}

problem there is that i have no idea how to create a new h2, get all the attributes etc. i'm sure theres a simple way to do that, any ideas?

like image 588
Mr. Etkin Avatar asked May 09 '11 11:05

Mr. Etkin


2 Answers

var headers = doc.DocumentNode.SelectNodes("//h1");
        if (headers != null)
        {
            foreach (HtmlNode item in headers)
            {
                item.Name = "h2"
            }
        }
like image 83
VikciaR Avatar answered Dec 23 '22 10:12

VikciaR


A similar approach replacing the tags using Descendants instead of SelectNodes:

IEnumerable<HtmlNode> tagDescendants = doc.DocumentNode.Descendants("h1");
foreach (HtmlNode htmlNode in tagDescendants)
{
    htmlNode.Name = "h2";
}
like image 44
Kirken Avatar answered Dec 23 '22 10:12

Kirken