如何存取網頁摘要 (HTML)

[ 本文的目標對象是撰寫 Windows 執行階段 App 的 Windows 8.x 和 Windows Phone 8.x 開發人員。如果您正在開發適用於 Windows 10 的 App,請參閱 最新文件 ]

本主題說明如何在 Windows 執行階段應用程式使用 Windows.Web.Syndication 命名空間的類別來抓取和顯示網頁摘要。

先決條件

下列範例使用 JavaScript,並且使用同步發佈範例做為依據。 如需使用 JavaScript 建立 Windows 執行階段應用程式的一般協助,請參閱使用 JavaScript 建立您的第一個 Windows 執行階段應用程式。另外,這個主題中使用 JavaScript Promise 來完成非同步操作。如需這種程式設計模式的詳細資訊,請參閱使用 Promise 在 JavaScript 的非同步程式設計

若要確保 Windows 執行階段應用程式的網路可正常運作,您必須在專案 Package.appxmanifest 檔案中設定所需的任何網路功能。 如果應用程式需要以用戶端的形式連線到網際網路上的遠端服務,則需要 [網際網路 (用戶端)] 功能。如果應用程式需要以用戶端的形式連線到家用網路或工作場所網路的遠端服務,則需要 [家中\公司網路]**** 功能。如需詳細資訊,請參閱如何設定網路功能

指示

從網頁摘要抓取同步發佈內容

現在我們要檢閱一些示範如何抓取摘要的程式碼,然後顯示摘要所包含的每一個個別項目。設定和傳送要求之前,我們會先定義一些要在作業期間使用的變數,然後初始化 SyndicationClient 的執行個體,這可定義要用來抓取和顯示摘要的方法和屬性。

如果傳遞給建構函式的 uriString 的不是有效 URI,Uri 建構函式會擲回例外狀況。所以我們要使用 try/catch 區塊來驗證 uriString

var currentFeed = null;
var currentItemIndex = 0;
        
var client = new Windows.Web.Syndication.SyndicationClient();

// The URI is validated by catching exceptions thrown by the Uri constructor.
var uri = null;
try {
    uri = new Windows.Foundation.Uri(uriString);
} catch (error) {
    WinJS.log && WinJS.log("Error: Invalid URI");
    return;
}

接下來,我們會透過設定所需的任何伺服器認證 (serverCredential 屬性)、Proxy 認證 (proxyCredential 屬性) 及 HTTP 標頭 (setRequestHeader 方法) 來設定要求。 設定好基本的要求參數之後,會使用應用程式提供的摘要 URI 字串建立有效的 Uri 物件。然後,將 Uri 物件傳遞到 retrieveFeedAsync 函式以要求摘要。

假設傳回所需的摘要內容,程式碼會逐一查看每個摘要項目,呼叫 displayCurrentItem (我們將在稍後定義),以便透過 UI 以清單方式顯示項目及其內容。

您必須編寫程式碼,在呼叫大多數非同步網路方法時處理例外狀況。您的例外狀況處理常式可以抓取例外狀況發生原因的更詳細資訊,更清楚地了解失敗的情況並作出適當的決定。如需詳細資訊,請參閱如何處理網路應用程式中的例外狀況

如果無法與 HTTP 伺服器建立連線或 Uri 物件沒有指向有效的 AtomPub 或 RSS 摘要,retrieveFeedAsync 方法會擲回例外狀況。如果發生錯誤,範例程式碼會使用 onError 函式來擷取例外狀況,然後列印出例外狀況中的詳細訊息。

function onError(err) {
    WinJS.log && WinJS.log(err, "sample", "error");

    // Match error number with a ErrorStatus value.
    // Use Windows.Web.WebErrorStatus.getStatus() to retrieve HTTP error status codes.
    var errorStatus = Windows.Web.Syndication.SyndicationError.getStatus(err.number);
    if (errorStatus === Windows.Web.Syndication.SyndicationErrorStatus.invalidXml) {
        displayLog("An invalid XML exception was thrown. Please make sure to use a URI that points to a RSS or Atom feed.");
    }
}

// Retrieve and display feed at given feed address.
function retreiveFeed(uri) {

    // Although most HTTP servers do not require User-Agent header, 
    // others will reject the request or return a different response if this header is missing.
    // Use the setRequestHeader() method to add custom headers.
    client.setRequestHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");

    client.retrieveFeedAsync(uri).done(function (feed) {
        currentFeed = feed;

        WinJS.log && WinJS.log("Feed download complete.", "sample", "status");

        var title = "(no title)";
        if (currentFeed.title) {
            title = currentFeed.title.text;
        }
        document.getElementById("CurrentFeedTitle").innerText = title;

        currentItemIndex = 0;
        if (currentFeed.items.size > 0) {
            displayCurrentItem();
        }

        // List the items.
        displayLog("Items: " + currentFeed.items.size);
     }, onError);
}

在上一個步驟中,retrieveFeedAsync 已傳回要求的摘要內容,而範例程式碼也順利地逐一查看可用的摘要項目。這些項目都會使用 SyndicationItem 物件來表示,而這個物件包含相關同步發佈標準 (RSS 或 Atom) 提供的所有項目屬性和內容。 在下列範例中,我們觀察到 displayCurrentItem 函式透過每個項目運作,且透過各種指定 UI 元素來顯示其內容。

function displayCurrentItem() {
    var item = currentFeed.items[currentItemIndex];

    // Display item number.
    document.getElementById("Index").innerText = (currentItemIndex + 1) + " of " + currentFeed.items.size;

    // Display title.
    var title = "(no title)";
    if (item.title) {
        title = item.title.text;
    }
    document.getElementById("ItemTitle").innerText = title;

    // Display the main link.
    var link = "";
    if (item.links.size > 0) {
        link = item.links[0].uri.absoluteUri;
    }

    var link = document.getElementById("Link");
    link.innerText = link;
    link.href = link;

    // Display the body as HTML.
    var content = "(no content)";
    if (item.content) {
        content = item.content.text;
    }
    else if (item.summary) {
        content = item.summary.text;
    }
    document.getElementById("WebView").innerHTML = window.toStaticHTML(content);

如同稍早的建議,SyndicationItem 物件所代表的內容類型會隨著發佈摘要所採用的摘要標準 (RSS 或 Atom) 而異。例如,Atom 摘要能夠提供 contributors 的清單,但是 RSS 摘要則無法提供。不過,您可以使用 SyndicationItem.elementExtensions 屬性,存取和顯示兩個標準都不支援的摘要項目所包含的延伸元素 (例如,Dublin Core 延伸元素),如下列範例程式碼所示範:


    // displayCurrentItem function continued
    var bindableNodes = [];
    for (var i = 0; i < item.elementExtensions.size; i++) {
        var bindableNode = {
            nodeName: item.elementExtensions[i].nodeName,
             nodeNamespace: item.elementExtensions[i].nodeNamespace,
             nodeValue: item.elementExtensions[i].nodeValue,
        };
        bindableNodes.push(bindableNode);
    }

    var dataList = new WinJS.Binding.List(bindableNodes);
    var listView = document.getElementById("extensionsListView").winControl;
    WinJS.UI.setOptions(listView, {
        itemDataSource: dataList.dataSource

    });
}

摘要與後續步驟

在這個主題中,我們抓取與提供的 URI 關聯的摘要,並逐項顯示摘要內容。

如需更多進階功能 (如在網頁摘要中新增、編輯和刪除項目的功能),請參閱如何管理網頁摘要項目

相關主題

其他

使用 Promise 在 JavaScript 的非同步程式設計

如何設定網路功能

如何處理網路應用程式中的例外狀況

如何管理網頁摘要項目

使用 JavaScript 建立 Windows 執行階段應用程式的藍圖

參考

SyndicationClient

SyndicationItem

Windows.Web.AtomPub

Windows.Web.Syndication

範例

AtomPub 範例

同步發佈範例