简体   繁体   English

如何使用linq读取xml文件

[英]How to read xml file using linq

I have this db.xml file 我有这个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>

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

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> : 最好使用强制转换(将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                   
            };

If you want Categories as List<string> then parse categories this way: 如果要将“ Categories作为List<string>则可以通过以下方式解析类别:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM