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

更新:我刚刚发现的例子从来就不是工作...我也读了示例代码后,得到了一个解决方案...我会后我为别人解决方案像我一样享受一次完成。

有帮助吗?

解决方案

下面是包含在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;
            }
        }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top