问题描述
|
我正在从sql Server检索许多网页的HTML(以前保存过)。我的目的是修改img的src属性。 HTML中只有一个img标记,其来源如下所示:
...
<td colspan=\"3\" align=\"center\">
<img src=\"/crossword/13cnum1.gif\" height=\"360\" width=\"360\" border=\"1\"><br></td>
...
我需要将/crossword/13cnum1.gif更改为http://www.nostrotech.com/crossword/13cnum1.gif
码:
private void Replacetest() {
String currentCode = string.Empty;
Cursor saveCursor = Cursor.Current;
try {
Cursor.Current = Cursors.WaitCursor;
foreach (WebData oneWebData in DataContext.DbContext.WebDatas.OrderBy(order => order.PuzzleDate)) {
if (oneWebData.Status == \"Done\" ) {
currentCode = oneWebData.Code;
#region Setup Agility
HtmlAgilityPack.HtmlDocument AgilityHtmlDocument = new HtmlAgilityPack.HtmlDocument {
OptionFixnestedTags = true
};
AgilityHtmlDocument.LoadHtml(oneWebData.PageData);
#endregion
#region Image and URL
var imageOnPage = from imgTags in AgilityHtmlDocument.DocumentNode.Descendants()
where imgTags.Name == \"img\" &&
imgTags.Attributes[\"height\"] != null &&
imgTags.Attributes[\"width\"] != null
select new {
Url = imgTags.Attributes[\"src\"].Value,tag = imgTags.Attributes[\"src\"],Text = imgTags.InnerText
};
if (imageOnPage == null) {
continue;
}
imageOnPage.FirstOrDefault().tag.Value = \"http://www.nostrotech.com\" + imageOnPage.FirstOrDefault().Url;
#endregion
}
}
}
catch (Exception ex) {
XtraMessageBox.Show(String.Format(\"Exception: \" + currentCode + \"!{0}Message: {1}{0}{0}Details:{0}{2}\",Environment.NewLine,ex.Message,ex.StackTrace),Text,MessageBoxButtons.OK,MessageBoxIcon.Error);
}
finally {
Cursor.Current = saveCursor;
}
}
我需要帮助,因为标记不是通过这种方式更新的,因此我需要将修改后的标记存储回数据库。谢谢。
解决方法
XPATH比所有这些XLinq行话都要简洁得多,恕我直言...
这是操作方法:
HtmlDocument doc = new HtmlDocument();
doc.Load(myHtml);
foreach (HtmlNode img in doc.DocumentNode.SelectNodes(\"//img[@src and @height and @width]\"))
{
img.SetAttributeValue(\"src\",\"http://www.nostrotech.com\" + img.GetAttributeValue(\"src\",null));
}
此代码搜索具有src
,height
和width
属性的img
标签。然后,它替换“ 4”属性值。