I have XML file quotes.xml. For my Windows Phone Project.
<?xml version="1.0" encoding="utf-8" ?>
<Motivation>
<Quotes>
<Quote Category ="Junk" Content='Alaa Alee Aluee'/>
<Quote Category ="Junk" Content='Alee Aleu Alue'/>
<Quote Category ="Junk" Content='Aluua Alue Aluee'/>
<Quote Category ="Junk" Content='Blaa Alee Aluee'/>
<Quote Category ="Jingalaga" Content='Bee Aleu Alue'/>
<Quote Category ="Jingalaga" Content='Bluua Alue Aluee'/>
<Quote Category ="Jingalaga" Content='Blaa Blee Bluee'/>
<Quote Category ="Jingalaga" Content='Blee Bleu Blue'/>
<Quote Category ="Jingalaga" Content='Bluua Blue Bluee'/>
<Quote Category ="Jingalaga" Content='Claa Clee Cluee'/>
<Quote Category ="Jingalaga" Content='Clee Cleu Clue'/>
<Quote Category ="Jingalaga" Content='Cluua Clue Cluee'/>
</Quotes>
</Motivation>
I want to access the Content by Each Category User Selects. If I have Value "Junk" from User, I am not able to get proper data as I expect.
var doc = XDocument.Load("Quotes.xml");
var quot = from var in doc.Descendants("Quote")
where var.Attribute("Category").Value == "Junk"
select new Quote
{
demo = var.Attribute("Content").Value
};
quot = quot.ToList();
cat.Text = quot.First().ToString();
I'm getting out put as Motivate.Quote. What I expect is "Alaa Alee Aluee" Also How can I be able to get random data as out put based on User click for more quote?
I suspect the problem is that you're creating an instance of Quote
, and not overridden ToString
in your Quote
class. Given that you're currently only pulling out the content anyway, I'd just create a List<string>
instead:
var quotes = XDocument.Load("Quotes.xml")
.Descendants("Quote")
.Where(x => (string) x.Attribute("Category") == "Junk")
.Select(x => (string) x.Attribute("Content"))
.ToList();
cat.Text = quotes.First();
If you do want to use a Quote
class, then you should probably specify all the details when creating the quote, and give the properties meaningful names:
var quotes = XDocument.Load("Quotes.xml")
.Descendants("Quote")
.Select(x => new Quote {
Content = (string) x.Attribute("Content"),
Category = (string) x.Attribute("Category")
})
.Where(q => q.Category == "Junk")
.ToList();
cat.Text = quotes.First().Content;
See more on this question at Stackoverflow