【问题标题】:HtmlAgilityPack example for changing links doesn't work. How do I accomplish this?用于更改链接的 HtmlAgilityPack 示例不起作用。我该如何做到这一点?
【发布时间】:2009-10-05 00:44:55
【问题描述】:

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

更新:我刚刚发现该示例永远不会起作用...阅读示例代码后我得到了解决方案...我会为其他人发布我的解决方案像我一样享受一旦完成。

【问题讨论】:

    标签: c# xpath uri html-agility-pack


    【解决方案1】:

    这是我基于 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;
                }
            }
    

    【讨论】:

    • 我想你也可以选择实际的属性节点:"//@background|//@lowsrc|//@src|//@href 并直接修改它们的Value 属性。您可以省去if 声明的级联。
    猜你喜欢
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    相关资源
    最近更新 更多