2

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

最初の問題は HtmlDocument です。DocumentElementが存在しません! 存在するのは HtmlDocument です。DocumentNode代わりにそれを使用しても、説明されているように href 属性にアクセスできません。次のエラーが表示されます。

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

このエラーが発生したときにコンパイルしようとしているコードは次のとおりです。

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

更新:この例が機能することを意図していないことがわかりました...そして、サンプルコードを読んだ後に解決策を見つけました...完了したら、私のような他の人が楽しめるように解決策を投稿します.

4

1 に答える 1

11

これは、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;
            }
        }
于 2009-10-07T15:17:35.357 に答える