在这个例子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;
}
}
文章来源: HtmlAgilityPack example for changing links doesn't work. How do I accomplish this?