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