Click here to Skip to main content
15,860,861 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to read a html file from specified path,then add custom attribute to html tags.for this I'm used from HtmlAgilityPack and this code:
C#
using HtmlAgilityPack;
using System;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Services;
using System.Web.UI.WebControls;

public partial class pages_send : System.Web.UI.Page
{
    static string htmlResult = "";
    protected void Page_Load(object sender, EventArgs e) {}

    [WebMethod(EnableSession = true)]
    public static object loadThemeBody(int ThemeID)
    {
        try
        {
            HtmlDocument document = new HtmlDocument();
            string path = HttpContext.Current.Server.MapPath(".") + "\\Theme.html";
            document.LoadHtml(HttpContext.Current.Server(path));

            HtmlNodeCollection mainNode = document.DocumentNode.ChildNodes;
            iterateNodes(mainNode);

            JavaScriptSerializer jss = new JavaScriptSerializer();

            jss.MaxJsonLength = Int32.MaxValue;

            return new { Result = "OK", Data = jss.Serialize(htmlResult) };
        }
        catch (Exception ex)
        {
            return new { Result = "FAILED", Message = ex.Message };
        }
    }
    public static void iterateNodes(HtmlNodeCollection htc)
    {
        try
        {
            foreach (var item in htc)
            {
                if (item.HasChildNodes)
                    iterateNodes(item.ChildNodes);
                else
                {
                    if (item.Name == "img")
                        item.Attributes.Add("class", "img");
                    if (item.Name == "a")
                        item.Attributes.Add("class", "a");
                }
                htmlResult = item.OuterHtml;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900