Replacing tags in HtmlAgility

吃可爱长大的小学妹 提交于 2019-12-22 05:10:07

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/5936116/replacing-tags-in-htmlagility

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!