HtmlAgilityPack改变链接无法正常工作的例子。我如何做到这一点? [英] HtmlAgilityPack example for changing links doesn't work. How do I accomplish this?

查看:211
本文介绍了HtmlAgilityPack改变链接无法正常工作的例子。我如何做到这一点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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属性的描述我收到以下错误:

The first issue is HtmlDocument.DocumentElement does not exist! What does exist is HtmlDocument.DocumentNode but even when I use that instead, I'm unable to access the href attribute as described. I get the following error:

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

下面是我想,当我得到这个错误编译代码:

Here's the code I'm trying to compile when I get this 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);
    }
}

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

UPDATE: I Just found that the example was never meant to work...And I've got a solution after reading the example code...I'll post my solution for other people like me to enjoy once completed.

推荐答案

下面是包含在ZIP我根据样本代码的部分快速的解决方案。

Here's my quick solution based on portions of the sample code included in the 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改变链接无法正常工作的例子。我如何做到这一点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆