sunero4
sunero4

Reputation: 840

Searching Xml Document with linq doesn't return anything

I'm trying to learn how to save and extract data with XML in C#, and even though I've read various answers to similar questions on here, I cannot get a hold of why my statement isn't returning anything. The program I'm writing is just a test, in which I've saved data about a couple movies in the xml document and now I'm trying to retrieve some of them based on their cost.

This is the class that I've written for searching:

 class ExtractData
{
    private XDocument _xdoc;
    public List<string> SearchByCost(double cost)
    {
        _xdoc = XDocument.Load(FileLocation.XmlFileLocation);
        List<string> list = new List<string>();

        var movies = from movie in _xdoc.Root.Elements("Name")
                where Convert.ToDouble(movie.Element("Cost").Value) < cost
                select movie;

        foreach (var item in movies)
        {
            list.Add(item.Value);
        }

        return list;
    }

}

This is how I'm trying to make it print it in the console:

        eData = new ExtractData();
        foreach (var movie in eData.SearchByCost(9))
        {
            Console.WriteLine(movie);
        }

And this is the content of the XML document:

<?xml version="1.0" encoding="utf-8"?>
<Movies>
  <Movie>
    <Id>1</Id>
    <Name>Shawshank Redemption</Name>
    <Director>Frank Darabont</Director>
    <Year>1994</Year>
    <Cost>9.95</Cost>
  </Movie>
  <Movie>
    <Id>2</Id>
    <Name>Pulp Fiction</Name>
    <Director>Quentin Tarantino</Director>
    <Year>1995</Year>
    <Cost>8.95</Cost>
  </Movie>
  <Movie>
    <Id>3</Id>
    <Name>Sharknado</Name>
    <Director>Anthony Ferrante</Director>
    <Year>2013</Year>
    <Cost>5.95</Cost>
  </Movie>
</Movies>

I hope this is enough information to try and help me out, and thanks in advance! :)

Upvotes: 2

Views: 100

Answers (2)

user1726343
user1726343

Reputation:

In plain English, you seem to be trying to find movies cheaper than 9 (of some arbitrary currency).

You can write this as:

public IReadOnlyCollection<string> SearchByCost(XDocument xdoc, double cost) 
{
    return xdoc.Root.Elements("Movie")
        .Where(movie => (double)movie.Element("Cost") < cost)
        .Select(movie => movie.Element("Name").Value)
        .ToList();
}

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

Root element contains Movie elements:

var movies = from movie in _xdoc.Root.Elements("Movie")  // here instead of "Name"
             where (double)movie.Element("Cost") < cost
             select movie;

Also, XElement supports explicit casting to double. And you can replace the second loop with LINQ query (assume you want to select names of movies):

List<string> list = movies.Select(m => (string)m.Element("Name")).ToList();

Upvotes: 4

Related Questions