軟體開發的天空


SINCE 2004

最新回應

剛好今天有位討論區的網友詢問如何解決上稿時及時檢測無障礙網頁內容的方法,
恰好之前在研究WebRequest取得網頁內容及特定剖析標籤內容,於是把那個已經生鏽的程式翻了出來加以修改一下.
也在BLOG做個筆記分享吧!

以下是初始網頁的Layout

檢測後取得結果內容的Layout

 網頁的ASPX內容Accessibility.aspx為:

<%@ Page Language="C#" AutoEventWireup="true" ValidateRequest="false" CodeFile="Accessibility.aspx.cs"
    Inherits="Accessibility" %>

<!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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        欲檢測網址:
        <asp:TextBox Style="width: 300px" ID="txtUrl" runat="server"></asp:TextBox><br />
        檢測結果:
        <asp:TextBox ID="txtResult" runat="server"></asp:TextBox><br />
        <asp:Button ID="btnSubmit" runat="server" Text="開始檢測" OnClick="Button1_Click" />
        <br />
        檢測結果內容:<br />
        <hr />
        <asp:Literal ID="Literal1" runat="server"></asp:Literal>
        </td> </tr> </table>
    </div>
    </form>
</body>
</html>

Code behind  Accessibility.aspx.cs

using System;

public partial class Accessibility : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string err="";
        string content="";
        string ExaminedUrl = txtUrl.Text;     //欲檢測的URL
        //欲檢測的URL,檢測等級,內容編碼
        CheckAccessibility a = new CheckAccessibility(ExaminedUrl,GradeEnum.APlus,ContentEncodingEnum.big5);
        a.PostActionUrl = "http://enable.nat.gov.tw/Servlet1";  //POST Action URL
        this.txtResult.Text = a.isVerified.ToString();           //是否已檢測通過
        content = a.ContentString;
        content = content.Replace(@"<img src=""images/report_title.gif", @"<img src=""http://enable.nat.gov.tw/images/report_title.gif");
        content = content.Replace(@"<a href = ""/", @"<a href = ""http://enable.nat.gov.tw/");                              
        Literal1.Text = content;   //POST後的頁面內容

    }

}

Reference 的類別 CheckAccessibility.cs

using System;
using System.IO;
using System.Net;
using System.Web;
using System.Xml;
using System.Xml.XPath;
using Sgml;


/// <summary>
/// CheckAccessibility 的摘要描述
/// </summary>

public class CheckAccessibility
{
    public CheckAccessibility(string ExaminedUrl, GradeEnum ExaminedGrade, ContentEncodingEnum ContentEncoding)
    {
        _ExaminedUrl = ExaminedUrl;                                            //檢測網址
        _ExaminedGrade = Enum.Format(typeof(GradeEnum), ExaminedGrade, "G");   //設定要檢測的無障礙等級
        _ContentEncoding = Enum.Format(typeof(ContentEncodingEnum), ContentEncoding, "G");//設定網頁內容的編碼
        if (_ContentEncoding.Equals("UTF8")) _ContentEncoding = "UTF-8";
    }

    /// <summary>
    /// 送出要檢測的網址及擷取檢測後的結果
    /// </summary>
    /// <returns></returns>

    private string GetURLRequest()
    {
        string _PostData;
        string _requestStr;
        _requestStr = "";
        System.Text.Encoding encode = System.Text.Encoding.GetEncoding(_ContentEncoding);
        _PostData = "?inputURL=" + _ExaminedUrl;
        _PostData += "&analyzingGrade=" + _ExaminedGrade;
        _PostData += "&isOnlyText=yes";
        _PostActionUrl += _PostData;
        try
        {
            HttpWebRequest t_req = WebRequest.Create(_PostActionUrl) as HttpWebRequest;
            t_req.Method = "GET";
            t_req.Timeout = 60000;
            //取得回應的內容
            WebResponse t_resp = t_req.GetResponse();
            StreamReader t_stream = new StreamReader(t_resp.GetResponseStream(), encode);
            _requestStr = t_stream.ReadToEnd().Trim();
        }

        catch (HttpException Httpex)
        { _ErrorMessage = Httpex.Message; }
        catch (WebException Webex)
        { _ErrorMessage = Webex.Message; }
        catch (IOException IOex)
        { _ErrorMessage = IOex.Message; }

        return _requestStr;
    }

    /// <summary>
    /// 檢測是否通過
    /// </summary>

    private void verified()
    {
        _ContentString = GetURLRequest();
        if (_ContentString.IndexOf("受測網頁已經通過") != -1)
        { _isVerified = true; }
        else { _isVerified = false; }
    }


    /// <summary>
    /// 擷取HTML的Tag標籤內容
    /// </summary>
    /// <param name="xpath"></param>
    /// <param name="err"></param>
    /// <returns></returns>

    public string ParsePage(string xpath, out string err)
    {
        err = string.Empty;
        string pageContent = _ContentString;
        string Result = "";
        StreamReader streamReader = null;
        StringWriter strWriter = null;
        SgmlReader sgmlReader = null;
        XmlTextWriter xmlWriter = null;
        try
        {
            sgmlReader = new SgmlReader();
            sgmlReader.DocType = "HTML";
            sgmlReader.InputStream = new StringReader(pageContent);
            strWriter = new StringWriter();
            xmlWriter = new XmlTextWriter(strWriter);
            xmlWriter.Formatting = Formatting.Indented;
            while (sgmlReader.Read())
            {
                if (sgmlReader.NodeType != XmlNodeType.Whitespace)
                {
                    xmlWriter.WriteNode(sgmlReader, true);
                }

            }

            string wellFormedHTML = strWriter.ToString();
            XPathDocument doc = new XPathDocument(new StringReader(wellFormedHTML));
            XPathNavigator nav = doc.CreateNavigator();
            XPathNodeIterator nodes = nav.Select(xpath);
            while (nodes.MoveNext())
            {
                Result += nodes.Current.Value + "\n";
            }

        }

        catch (Exception exp)
        {
            err = exp.ToString();
        }


        return Result;
    }

    成員屬性
}

    列舉