RSS/Atom フィード

重要な API

Windows.Web.Syndication 名前空間の機能を使用して、RSS および Atom 標準に準拠して生成された配信フィードを利用し、最新かつ人気のある Web コンテンツを取得または作成します。

Note

Windows.Web.Syndication API と Windows.Web.AtomPub API は、WinUI 3 (Windows アプリ SDK) デスクトップ アプリおよび UWP アプリで動作する Windows ランタイム (WinRT) API です。

フィードとは

Web フィードは、テキスト、リンク、画像で構成される任意の数の個々のエントリを含むドキュメントです。 フィードに対して行われた更新は、Web 全体で最新のコンテンツを宣伝するために使用される新しいエントリの形式です。 コンテンツ コンシューマーは、フィード リーダー アプリを使用して、任意の数の個々のコンテンツ作成者からのフィードを集計および監視し、最新のコンテンツにすばやく便利にアクセスできます。

サポートされているフィード形式の標準はどれですか?

Windowsでは、0.91 から RSS 2.0 までの RSS 形式標準と、0.3 から 1.0 までの Atom 標準のフィード取得がサポートされています。 Windows内のクラス。Web.Syndication 名前空間では、RSS 要素と Atom 要素の両方を表すことができるフィードとフィード項目を定義できます。

さらに、Atom 1.0 形式と RSS 2.0 形式の両方で、フィード ドキュメントに公式仕様で定義されていない要素または属性を含めることができます。 これらのカスタム要素と属性は、時間の経過とともに、GData や OData などの他の Web サービス データ形式で使用されるドメイン固有の情報を定義する方法になりました。 この追加された機能をサポートするために、 SyndicationNode クラスは汎用 XML 要素を表します。 Windows.Data.Xml.Dom 名前空間のクラスと共に SyndicationNode を使用すると、アプリは属性、拡張、およびそれらに含まれるあらゆるコンテンツにアクセスできます。

シンジケートコンテンツの公開については、Atomパブリケーションプロトコル(WindowsのWindows実装であることに注意してください。Web.AtomPub) では、Atom と Atom Publication の標準に従ったフィード コンテンツ操作のみがサポートされます。

ネットワーク分離でのシンジケート コンテンツの使用

Windowsのネットワーク分離機能を使用すると、開発者はWindows アプリによるネットワーク アクセスを制御および制限できます。 すべてのアプリがネットワークへのアクセスを必要とするわけではありません。 ただし、実行するアプリの場合、Windowsは、適切な機能を選択することで有効にできるさまざまなレベルのネットワークアクセスを提供します。

ネットワークの分離により、開発者はアプリごとに必要なネットワーク アクセスのスコープを定義できます。 適切なスコープが定義されていないアプリは、指定された種類のネットワークおよび特定の種類のネットワーク要求 (送信クライアントが開始した要求、または要求されていない受信要求と送信クライアント開始要求の両方) にアクセスできなくなります。 ネットワーク分離を設定して適用する機能により、アプリが侵害された場合、アプリが明示的にアクセスを許可されているネットワークにのみアクセスできるようになります。 これにより、他のアプリケーションやWindowsへの影響の範囲が大幅に削減されます。

ネットワーク分離は、Windows.Web.Syndication および Windows.Web.AtomPub 名前空間内でネットワークへのアクセスを試みるすべてのクラス要素に影響します。 Windowsでは、ネットワーク分離がアクティブに適用されます。 Windows.Web.Syndication または Windows.Web.AtomPub 名前空間内のクラス要素の呼び出しでネットワーク アクセスが発生するものは、適切なネットワーク機能が有効になっていない場合、ネットワーク分離のために失敗する可能性があります。

アプリのネットワーク機能は、アプリのビルド時にアプリ マニフェストで構成されます。 ネットワーク機能は、通常、アプリの開発時にVisual Studioを使用して追加されます。 ネットワーク機能は、テキスト エディターを使用してアプリ マニフェスト ファイルで手動で設定することもできます。

ネットワークの分離とネットワーク機能の詳細については、「ネットワークの基本」トピックの「機能」セクション 参照してください。

Web フィードにアクセスする方法

このセクションでは、Windowsのクラスを使用して Web フィードを取得して表示する方法について説明します C# で記述されたWindows アプリの Web.Syndication 名前空間。

前提条件

Windows アプリがネットワークに対応していることを確認するには、Package.appxmanifest ファイルで必要なネットワーク機能を設定する必要があります。 アプリをクライアントとしてインターネット上のリモート サービスに接続する必要がある場合は、 internetClient 機能が必要です。 詳細については、「ネットワークの基本」トピックの「機能」セクション 参照してください。

Web フィードからの配信コンテンツの取得

次に、フィードを取得し、フィードに含まれる各アイテムを表示する方法を示すコードをいくつか確認します。 要求を構成して送信する前に、操作中に使用するいくつかの変数を定義し、 SyndicationClient のインスタンスを初期化します。これは、フィードの取得と表示に使用するメソッドとプロパティを定義します。

Uri コンストラクターに渡された uriString が有効な URI でない場合、Uri コンストラクターは例外をスローします。 そのため、try/catch ブロックを使用して uriString を 検証します。

Windows.Web.Syndication.SyndicationClient client = new Windows.Web.Syndication.SyndicationClient();
Windows.Web.Syndication.SyndicationFeed feed;
// The URI is validated by catching exceptions thrown by the Uri constructor.
Uri uri = null;
// Use your own uriString for the feed you are connecting to.
string uriString = "";
try
{
    uri = new Uri(uriString);
}
catch (Exception ex)
{
    // Handle the invalid URI here.
}

Note

この記事の JavaScript サンプルでは、UWP JavaScript アプリのレガシ フレームワークである WinJS (JavaScript 用の Windows ライブラリ) を使用します。 これらのサンプルは参照用にのみ提供され、新しいアプリ開発には推奨されません。

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 プロパティ)、プロキシ資格情報 ( ProxyCredential プロパティ)、HTTP ヘッダー ( SetRequestHeader メソッド) を設定して要求を構成します。 基本的な要求パラメーターが構成 された状態で 、アプリによって提供されるフィード URI 文字列を使用して作成された有効な URI オブジェクト。 その後、 Uri オブジェクトが RetrieveFeedAsync 関数に渡され 、フィードが要求されます。

目的のフィード コンテンツが返されたと仮定すると、サンプル コードは各フィード項目を反復処理し、 displayCurrentItem (次に定義します) を呼び出して、UI を介して項目とその内容をリストとして表示します。

ほとんどの非同期ネットワーク メソッドを呼び出すときに例外を処理するコードを記述する必要があります。 例外ハンドラーは、例外の原因に関するより詳細な情報を取得して、エラーをよりよく理解し、適切な決定を行うことができます。

RetrieveFeedAsync メソッドは、HTTP サーバーとの接続を確立できなかった場合、または Uri オブジェクトが有効な AtomPub または RSS フィードを指していない場合に例外をスローします。 JavaScript サンプル コードでは 、onError 関数を使用して例外をキャッチし、エラーが発生した場合は例外に関する詳細情報を出力します。

try
{
    // 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)");
    feed = await client.RetrieveFeedAsync(uri);
    // Retrieve the title of the feed and store it in a string.
    string title = feed.Title.Text;
    // Iterate through each feed item.
    foreach (Windows.Web.Syndication.SyndicationItem item in feed.Items)
    {
        displayCurrentItem(item);
    }
}
catch (Exception ex)
{
    // Handle the exception here.
}
function onError(err) {
    WinJS.log && WinJS.log(err, "sample", "error");
    // Match error number with an 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 は要求されたフィード コンテンツを返し、サンプル コードは使用可能なフィード項目の反復処理を行う必要があります。 これらの各項目は、関連する配信標準 (RSS または Atom) によって提供されるすべての項目プロパティとコンテンツを含む SyndicationItem オブジェクトを使用して表されます。 次の例では、 displayCurrentItem 関数が各項目を操作し、さまざまな名前付き UI 要素を通じてそのコンテンツを表示しているのを確認します。

private void displayCurrentItem(Windows.Web.Syndication.SyndicationItem item)
{
    string itemTitle = item.Title == null ? "No title" : item.Title.Text;
    string itemLink = item.Links == null ? "No link" : item.Links.FirstOrDefault().ToString();
    string itemContent = item.Content == null ? "No content" : item.Content.Text;
    //displayCurrentItem is continued below.
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 linkElement = document.getElementById("Link");
    linkElement.innerText = link;
    linkElement.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);
                //displayCurrentItem is continued below.

前述のように、 SyndicationItem オブジェクトによって表されるコンテンツの種類は、フィードの公開に使用されるフィード標準 (RSS または Atom) によって異なります。 たとえば、Atom フィードは 共同作成者のリストを提供できますが、RSS フィードは提供されません。 ただし、いずれかの標準 (Dublin Core 拡張要素など) でサポートされていないフィード項目に含まれる拡張要素には、 SyndicationItem.ElementExtensions プロパティを使用してアクセスし、次のコード例に示すように表示できます。

    //displayCurrentItem continued.
    string extensions = "";
    foreach (Windows.Web.Syndication.SyndicationNode node in item.ElementExtensions)
    {
        string nodeName = node.NodeName;
        string nodeNamespace = node.NodeNamespace;
        string nodeValue = node.NodeValue;
        extensions += nodeName + "\n" + nodeNamespace + "\n" + nodeValue + "\n";
    }
    this.listView.Items.Add(itemTitle + "\n" + itemLink + "\n" + itemContent + "\n" + extensions);
}
    // 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
    });
}