1

I have this db.xml file

<items> <item> <title>Title1</title> <year>2013</title> <categories> <category>Category1</category> <category>Category2</category> <category>Category3</category> </categories> <count>10</count> </item> (and so on) </items> 

I read like that:

var items = from item in xdoc.Descendants("item") select new { Title = item.Element("title").Value, Year = item.Element("year").Value, Categories = item.Element("categories").Value, // I know this is wrong Count = item.Element("count").Value }; 

The problem is how I can read the categories and add them to list?

foreach (var item in items) { book.Title = item.Title; book.Year = item.Year; foreach (var Category in Categories) { book.Categories.Add(Category); } book.Count = item.Count; books.Add(book); } 
1
  • You just need to do the same as you did with the first one, just nest it inside, the principle remains the same Commented Mar 21, 2013 at 13:27

2 Answers 2

5

It's better to use casting (to string, to int, etc then reading element's value directly. Here is query which returns integer values for Year and Count properties. Categories are IEnumerable<string>:

var items = from item in xdoc.Descendants("item") select new { Title = (string)item.Element("title"), Year = (int)item.Element("year"), Count = (int)item.Element("count"), Categories = from c in item.Element("categories").Elements() select (string)c }; 

If you want Categories as List<string> then parse categories this way:

 Categories = item.Element("categories") .Elements() .Select(c => (string)c) .ToList() 
Sign up to request clarification or add additional context in comments.

Comments

4

You can take the list of its elements

EDITED

var items = from item in xdoc.Descendants("item") select new { Title = item.Element("title").Value, Year = item.Element("year").Value, Categories = item.Descendants("categories").Descendants().Select(x=>x.Value).ToList(), Count = item.Element("count").Value }; 

6 Comments

I think this query will produce wrong result. Instead of selecting categories you are returning whole parent element value
@lazyberezovsky Why? Wont it return the list of categories Descendants?
Query is incorrect: Categories is List<string> with just one value: Category1Category2Category3.
@MarcinJuraszek Yep, sorry, missed one Descendants() - answer updated
@lazyberezovsky Yep, sorry, missed one Descendants() - answer updated
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.