Pregunta

El ejemplo de CodePlex es la siguiente:

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

La primera cuestión es HtmlDocument. DocumentElement no existe! Lo que sí existe es HtmlDocument. DocumentNode pero incluso cuando uso que en lugar, soy incapaz de acceder al atributo href como se describe. Me sale el siguiente error:

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

Este es el código que estoy tratando de recopilar cuando me sale este 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);
    }
}

ACTUALIZACIÓN: Me acabo de enterar que el ejemplo no estaba destinado a trabajar ... Y tengo una solución después de leer el código de ejemplo ... Voy a publicar mi solución para otras personas como yo para disfrutar una vez terminado.

¿Fue útil?

Solución

Aquí está mi solución rápida en base a porciones del código de ejemplo incluido en el 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;
            }
        }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top