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;
}
}
이 방법으로 마크 업이 업데이트되지 않고 수정 된 마크 업을 다시 DB에 저장해야하므로 도움이 필요합니다. 감사.
XPATH는이 모든 XLinq 전문 용어보다 훨씬 더 중요합니다. IMHO ... 여기에 그것을 수행하는 방법이 있습니다.
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
태그를 검색합니다. 그런 다음 src
속성 값을 대체합니다.