みなさん、辞書で単語を検索し(クエリ文字列でURLを取得)、結果をプレースホルダーに挿入し、辞書Webサイトからcssファイルを取得してそのコンテンツを適切にフォーマットする単純なaspx Webページを作成しています。
どうやら3番目のポイントを解決する方法がわかりません。実際、複数のアプローチを試しましたが、うまくいかないようです。
正確には、適切な css ファイルへのリンクを正常に取得し、それをページ ヘッダーに挿入しました (試行: Page_load、Page_Init イベント)。クエリ結果は、Button_click イベント ハンドラーの「resultpanel」プレース ホルダーに挿入されます。
また、対応する分離コード ファイルが続く ASPX マークアップも含めました。このプロジェクトでは HtmlAgilityPack を使用します。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Multidictionary.Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:PlaceHolder runat="server" id="hdr"></asp:PlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>
Enter URL and get contents of the page</h3>
<asp:textbox id="TextBoxURL" runat="server" height="20px" width="250px" text="http://www.vandale.nl/opzoeken?pattern=kat&lang=nn">
</asp:textbox>
<asp:button id="Button1" runat="server" text="Get Contents" onclick="Button1_Click" />
<br />
<asp:literal runat="server" id="resultpanel"></asp:literal>
</div>
</form>
</body>
</html>
コードビハインド
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using HtmlAgilityPack;
using System.Web.UI.HtmlControls;
namespace Multidictionary
{
public partial class Default : System.Web.UI.Page
{
private string dictionaryUrl = "http://www.vandale.nl";
private IEnumerable<HtmlNode> csslink;
protected void Page_Init(object sender, EventArgs e)
{
}
protected void Page_Load(object sender, EventArgs e)
{
//your code
string url = TextBoxURL.Text;
var webGet = new HtmlWeb();
var document = webGet.Load(url);
csslink = (from el in document.DocumentNode.SelectNodes("//link[@type='text/css']")
where
(el.Attributes["rel"] != null) && ("stylesheet".Equals(el.Attributes["rel"].Value))
select el);
if (csslink != null && csslink.Count() > 0)
{
HtmlLink cssLink = new HtmlLink();
cssLink.Href = dictionaryUrl + csslink.FirstOrDefault().Attributes["href"].Value;//"path to CSS";
cssLink.Attributes["type"] = "text/css";
cssLink.Attributes["media"] = "all";
hdr.Controls.Add(cssLink);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string url = TextBoxURL.Text;
var webGet = new HtmlWeb();
var document = webGet.Load(url);
var definitieDiv = from el in document.DocumentNode.Descendants()
where (el.Attributes["id"] != null) && ("content-area".Equals(el.Attributes["id"].Value))
select el;
if (definitieDiv != null && definitieDiv.Count() > 0)
{
resultpanel.Text = definitieDiv.FirstOrDefault().OuterHtml;
}
}
}
}
私の質問に明確な説明が必要な場合は、遠慮なく私に連絡してください。