rsssvelteatom-feed

How can I read an atom feed using svelte?


I'm currently learning Svelte and I would like to parse an atom feed and render it on the screen, but I'm not sure how to start getting the feed in. Can someone point me in the right direction on how to do this with Svelte?


Solution

  • This is pretty unrelated to Svelte, the main two things are:

    Once you have an object representation of the feed it can be rendered using Svelte like any other object.

    If you want to do this fully client-side, including getting the feed-content, e.g. via fetch, you will probably run into cross-origin issues, depending on where the feed is from. So you might have to fetch the feed on the server and pass it to the client.

    To parse the feed you can e.g. use the DOMParser:

    const feedDocument = new DOMParser().parseFromString(atomXmlText, 'text/xml')
    

    The resulting object is a DOM document that can be traversed or queried like an HTML document.


    Basic example:

    <script>
        let items = [];
        async function load() {
            const res = await fetch('...');
            const text = await res.text();
            const feedDocument = new DOMParser().parseFromString(text, 'text/xml')
            items = [...feedDocument.querySelectorAll('entry')].map(item => {
                const title = item.querySelector('title').textContent;
                const url = item.querySelector('link').attributes['href'].value;
                
                return { title, url };
            });
        }
        load()
    </script>
    
    <ul>
        {#each items as { title, url }}
            <li>
                <a href={url} target="_blank" rel="noreferrer noopener">
                    {title}
                </a>
            </li>
        {/each}
    </ul>
    

    REPL

    (I could not find a proper feed with the correct CORS headers to allow a fetch, so the REPL does not actually fetch() anything.)

    RSS example for NY Times (May break at any point)