HtmlAgilityPack example for changing links doesn't work. How to do it?

Example codeplex :

HtmlDocument doc = new HtmlDocument();
 doc.Load("file.htm");
 foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[@href"])
 {
    HtmlAttribute att = link["href"];
    att.Value = FixLink(att);
 }
 doc.Save("file.htm");

      

The first problem is HtmlDocument. DocumentElement doesn't exist! What exists is HtmlDocument. DocumentNode , but even when I use that instead, I cannot access the href attribute as described. I am getting the following error:

Cannot apply indexing with [] to an expression of type 'HtmlAgilityPack.HtmlNode'

      

Here is the code I'm trying to compile when I get this error:

private static void ChangeUrls(ref HtmlDocument doc)
{
    foreach(HtmlNode link in doc.DocumentNode.SelectNodes("//@href"))
    {
        HtmlAttribute attr = link["href"];
        attr.Value = Rewriter(attr.Value);
    }
}

      

UPDATE: I just found the example was never supposed to work ... And I have a solution after reading the example code ... I'll post my solution to other people as I enjoy after completing.

+2


source to share


1 answer


Here's my quick solution based on the sample code parts included in the ZIP.



private static void ChangeLinks(ref HtmlDocument doc)
        {
            if (doc == null) return;
            //process all tage with link references
            HtmlNodeCollection links = doc.DocumentNode.SelectNodes("//*[@background or @lowsrc or @src or @href]");
            if (links == null)
                return;

            foreach (HtmlNode link in links)
            {

                if (link.Attributes["background"] != null)
                    link.Attributes["background"].Value = _newPath + link.Attributes["background"].Value;
                if (link.Attributes["href"] != null)
                    link.Attributes["href"].Value = _newPath + link.Attributes["href"].Value;(link.Attributes["href"] != null)
                    link.Attributes["lowsrc"].Value = _newPath + link.Attributes["href"].Value;
                if (link.Attributes["src"] != null)
                    link.Attributes["src"].Value = _newPath + link.Attributes["src"].Value;
            }
        }

      

+11


source







All Articles