Lone Starr
Lone Starr

Reputation: 65

Load Xdocument with RSS feed in MVVM app

I am learning MVVM & Linq to xml by converting a simple wpf RSS app. Originally, I used XmlDataProvider to load local xml files or RSS urls. I am now using the code below which works fine loading local xml files, but throws the "FileNotFoundException" when its a url. During debugging I see the correct url address in (string RSS_URL), yet the file is not found. My initial searching led me to Webclient & HttpWebRequest, but I haven't had any success with them. Am I on the right track? Any code or tutorial links available?

public static List<RSSItem> Load(string RSS_URL)
    {
        if (!File.Exists(RSS_URL))
        {
            throw new FileNotFoundException("Datasource file could not be found", RSS_URL);
        }

        var rssfiles = XDocument.Load(RSS_URL).Descendants("item").Select(
            x => new RSSItem(
                (string)x.Element("title"),
                (string)x.Element("link"),
                (string)x.Element("description"))); 

        return rssfiles.ToList();
    }

Thank You

Upvotes: 2

Views: 1742

Answers (2)

remarkrm
remarkrm

Reputation: 159

XDocument.Load() will accept URLs without any problem. The issue in your code is that you're using File.Exists() to determine whether or not he URL is valid. File.Exists() only accepts a filesystem path, not a uri.

Quick piece of additional info: the Load() method relies on an underlying XmlReader and a call to Create(). If the resource (the URL in this case) doesn't exist, a WebException will be thrown indicating that the resource doesn't exist.

XDocument.Load info: http://msdn.microsoft.com/en-us/library/bb343181.aspx

XmlReader.Create info: http://msdn.microsoft.com/en-us/library/w8k674bf.aspx

Upvotes: 2

Peter Monks
Peter Monks

Reputation: 4399

The XDocument.Load overload you are using is specifically for loading from a file. You would have to download from the RSS feed to get the XML data locally. Look at the MSDN document here for alternatives such as reading from a stream, which might be better suited to what you need.

Upvotes: 0

Related Questions