开发者

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

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")
       开发者_JS百科            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?


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜