private static string ConvertToAbsoluteUrls (string html, Uri relativeLocation) {
IHTMLDocument2 doc = new HTMLDocumentClass ();
doc.write (new object [] { html });
doc.close ();
foreach (IHTMLAnchorElement anchor in doc.links) {
IHTMLElement element = (IHTMLElement)anchor;
string href = (string)element.getAttribute ("href", 2);
if (href != null) {
Uri addr = new Uri (relativeLocation, href);
anchor.href = addr.AbsoluteUri;
}
}
foreach (IHTMLImgElement image in doc.images) {
IHTMLElement element = (IHTMLElement)image;
string src = (string)element.getAttribute ("src", 2);
if (src != null) {
Uri addr = new Uri (relativeLocation, src);
image.src = addr.AbsoluteUri;
}
}
string ret = doc.body.innerHTML;
return ret;
}
IHTMLDocument2 doc = new HTMLDocumentClass ();
doc.write (new object [] { html });
doc.close ();
foreach (IHTMLAnchorElement anchor in doc.links) {
IHTMLElement element = (IHTMLElement)anchor;
string href = (string)element.getAttribute ("href", 2);
if (href != null) {
Uri addr = new Uri (relativeLocation, href);
anchor.href = addr.AbsoluteUri;
}
}
foreach (IHTMLImgElement image in doc.images) {
IHTMLElement element = (IHTMLElement)image;
string src = (string)element.getAttribute ("src", 2);
if (src != null) {
Uri addr = new Uri (relativeLocation, src);
image.src = addr.AbsoluteUri;
}
}
string ret = doc.body.innerHTML;
return ret;
}
本文介绍了一个用于将HTML文档中的所有相对URL转换为绝对URL的实用方法。通过利用COM组件IHTMLDocument2,该方法遍历文档中的链接和图片元素,更新其href和src属性,确保所有资源引用都是完整的绝对路径。

被折叠的 条评论
为什么被折叠?



