2012-01-18 25 views
2

我正在使用HtmlAgilityPack從網頁中檢索信息,並且目前正在使用按鈕單擊方法中的ListView控件在頁面上顯示值。如何在asp.net中的SQL表中存儲IEnumerable <>數據值?

protected void Button1_Click(object sender, EventArgs e) 
{ 
    string url = TextBox1.Text.ToString(); 
    var webGet = new HtmlWeb(); 
    var document = webGet.Load(url); 
    // Below code crawl the data and store in generic IEnumerable<T> fashion // 
    var TheWeb = 
      from info in document.DocumentNode.SelectNodes("//div[@class='article-listing']//div[@class='media-data']") 
      from link in info.SelectNodes("h4//a").Where(x => x.Attributes.Contains("href")) 
      from content in info.SelectNodes("p").Where(y => y.HasAttributes != true) 
      from author in info.SelectNodes("p[@class='article-meta']//a[@rel='author']").Where(z => z.Attributes.Contains("href")) 
      from date in info.SelectNodes("p[@class='article-meta']//span") 
      select new 
      { 
       LinkURL = link.Attributes["href"].Value, 
       Text = content.InnerText, 
       Author = author.InnerText, 
       Date = date.InnerText 
      }; 
    lvLinks.DataSource = TheWeb; 
    lvLinks.DataBind(); 
} 

但現在我要存儲在SQL Server中的數據,並希望運行使用某些功能(而不是按一下按鈕)的代碼。

爲此,我想以某種其他形式存儲數據,而不是使用LINQ提取值的IEnumerable樣式。

請建議。

回答

3

你可以有一個自定義的類結構

public class ParseData 
{ 
    public string LinkURL { get; set; } 
    public string Text { get; set; } 
    public string Author { get; set; } 
    public string Date { get; set; } 
} 

與您的查詢

var TheWeb = 
     from info in document.DocumentNode.SelectNodes("//div[@class='article-listing']//div[@class='media-data']") 
     from link in info.SelectNodes("h4//a").Where(x => x.Attributes.Contains("href")) 
     from content in info.SelectNodes("p").Where(y => y.HasAttributes != true) 
     from author in info.SelectNodes("p[@class='article-meta']//a[@rel='author']").Where(z => z.Attributes.Contains("href")) 
     from date in info.SelectNodes("p[@class='article-meta']//span") 
     select new ParseData 
     { 
      LinkURL = link.Attributes["href"].Value, 
      Text = content.InnerText, 
      Author = author.InnerText, 
      Date = date.InnerText 
     }; 
var parseData = TheWeb.ToList(); 

現在使用System.Xml.Serialization.XmlSerializer序列化此數據在XML填充它。將此XML存儲在數據庫中,並在需要時進行檢索。

Tutorial explaining how to Serialize object in XML and Deserialize back to object

希望這對你有用。

1

最小干擾的方式:

var IcanbeQueried = myIEnumerable.AsQueryable(); 

然後你就可以保持你的代碼,你只需要將其轉換爲一個IQueryable像這樣。

相關問題