2011-05-24 82 views
2

我正在从SQL Server中检索许多网页(之前保存的)的HTML。我的目的是修改一个img的src属性。只有一个在HTML img标签,它的来源是像这样:需要用新值替换img src attrib

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

我需要帮助的标记不更新这个娃我和我需要将修改后的标记存回数据库。谢谢。

回答

8

XPATH比这一切XLINQ行话更consise,恕我直言... 这里是如何做到这一点:

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

此代码搜索有srcheightwidth属性img标签。然后,它将替换src属性值。