Reading XML data using LINQ, multiple elements with the same name

自作多情 提交于 2020-01-03 02:29:29

问题


Visual Studio 2010, Silverlight 4, and C#. I have the following data stored in an XML file:

<root>
      <element>TextHere</element>
      <element>TextHere</element>
      <element>TextHere</element>
</root>

This is my current code.

XDocument xmlDoc = XDocument.Load("XMLDocument.xml");
var ElementsList = from Elements in xmlDoc.Descendants("root")
                   select new
                   {
                       ElementContent = Elements.Element("Element").Value,
                   };

This code only puts the very first element in the list, leaving all of the others out. How can I rewrite this code so that it will capture ALL of the elements that are named "element" in the XML file?


回答1:


This would do it:

XDocument xmlDoc = XDocument.Load("XMLDocument.xml");
var ElementsList = from Elements in xmlDoc.Descendants("element")
                   select new
                   {
                       ElementContent = Elements.Value
                   };

Or a little more succinct in dot notation:

var ElementsList = xmlDoc.Descendants("element")
                         .Select(x => new { ElementContent = x.Value });

Note however that you only have an enumeration of elements after this, if you want a list (as your variable name suggests) you can add a .ToList() after the Select:

var ElementsList = xmlDoc.Descendants("element")
                         .Select(x => new { ElementContent = x.Value })
                         .ToList();

This will list will contain 3 elements (based on your example XML. ) of an anonymous type that has a ElementContent property. If you do not need that property (and I would think you don't) this is a simplified version that just returns a list of string:

var ElementsList = xmlDoc.Descendants("element")
                         .Select(x => x.Value)
                         .ToList();



回答2:


This would do it-

 XDocument xmlDoc = XDocument.Load("XMLDocument.xml");
 var ElementsList = from Elements in xmlDoc.Descendants("root")
 select new
 {
   Element1 = (string)Elements.Element("element"),
   Element2 = Elements.Element("element").ElementsAfterSelf("element").First().Value,
   Element3 = Elements.Element("element").ElementsAfterSelf("element").ElementAt(1).Value,
 };


来源:https://stackoverflow.com/questions/5012186/reading-xml-data-using-linq-multiple-elements-with-the-same-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!