如何在具有XDocument的节点中获取具有相同名称的多个元素?

时间:2013-06-17 12:05:28

标签: c# xml xml-parsing linq-to-xml

我有一个带有这个结构的xml:

   <news>
      <id><![CDATA[1]]></id>
      <title><![CDATA[My title]]></title>
      <date><![CDATA[17-06-2013]]></date>
      <machine><![CDATA[a]]></machine>
      <machine><![CDATA[b]]></machine>
      <machine><![CDATA[c]]></machine>
      <machine><![CDATA[d]]></machine>
   </news>
   <news>
      <id><![CDATA[2]]></id>
      <title><![CDATA[My title 2]]></title>
      <date><![CDATA[17-06-2013]]></date>
      <machine><![CDATA[a]]></machine>
      <machine><![CDATA[b]]></machine>
      <machine><![CDATA[c]]></machine>
      <machine><![CDATA[d]]></machine>
   </news>

我这样读了:

var datas = from query in loadedData.Descendants("news")
                            select new News
                            {
                                Title = (string)query.Element("title"),
                                Id = (string)query.Element("id"),
                                StrDate = (string)query.Element("date"),
                                list = query.Elements("machine")
                            };

代码

list = query.Elements("machine")

不起作用。如何获取包含带有“machine”标签的元素的列表

1 个答案:

答案 0 :(得分:1)

下面提到的代码应该可行。我已将列表视为List

的对象
var datas = from query in loadedData.Descendants("news")
                                select new News
                                {
                                    Title = (string)query.Element("title"),
                                    Id = (string)query.Element("id"),
                                    StrDate = (string)query.Element("date"),
                                    list = (from xele in query.Descendants("machine")
                                           select xele.Value).ToList<string>();   
                                };