HtmlAgilityPack سبيل المثال تغيير الروابط لا تعمل.كيف يمكنني تحقيق ذلك ؟

StackOverflow https://stackoverflow.com/questions/1517804

سؤال

مثال على 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);
    }
}

تحديث: أنا فقط وجدت هذا المثال لم يكن من المفترض أن تعمل...و أنا عندي الحل بعد قراءة التعليمة البرمجية الموجودة في المثال...أنا ما الحل الآخرين مثلي التمتع مرة واحدة الانتهاء.

هل كانت مفيدة؟

المحلول

هنا هو بلدي حل سريع على أساس أجزاء من نموذج التعليمة البرمجية المضمنة في الرمز البريدي.

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