如何使用linq读取xml文件

时间:2013-03-21 13:23:27

标签: c# xml winforms linq class

我有这个db.xml文件

<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>

我读的那样:

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
           };

问题是我如何读取类别并将它们添加到列表中?

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);
}

2 个答案:

答案 0 :(得分:5)

最好使用强制转换(stringint等,然后直接读取元素的值。这是查询返回YearCount属性的整数值。CategoriesIEnumerable<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                   
            };

如果您希望CategoriesList<string>,请按以下方式解析类别:

 Categories = item.Element("categories")
                  .Elements()
                  .Select(c => (string)c)
                  .ToList()

答案 1 :(得分:4)

您可以获取其元素列表

<强> 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
       };