2009-10-05 5 views
2

codeplex의 예제는 다음과 같습니다.링크를 변경하는 HtmlAgilityPack 예제가 작동하지 않습니다. 어떻게해야합니까?

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); 
    } 
} 
업데이트 : ... 그리고 예제 코드를 읽은 후 해결책을 얻었습니다 ... 마치 한 번 완성 된 것을 즐기는 다른 사람들을위한 솔루션을 게시 할 것입니다.

답변

11

다음은 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; 
      } 
     } 
+0

실제 속성 노드 인''// background | // @ lowsrc | // @ src | // @ href'를 선택해서 'Value' 속성을 직접 수정할 수도 있습니다. 'if' 문장의 계단을 스스로 예비하십시오. – Tomalak

+0

나는 그것을 시험해 볼 것입니다. 감사합니다. –

관련 문제