简体   繁体   English

使用LINQ读取XML数据,多个具有相同名称的元素

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

Visual Studio 2010, Silverlight 4, and C#. Visual Studio 2010,Silverlight 4和C#。 I have the following data stored in an XML file: 我将以下数据存储在XML文件中:

<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? 如何重写此代码,以便捕获XML文件中所有名为“元素”的元素?

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: 但是请注意,此后仅包含一个元素枚举,如果您想要一个列表(如变量名所示),则可以在Select之后添加.ToList()

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. 该列表将包含3个具有ElementContent属性的匿名类型的元素(基于您的示例XML。)。 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,
 };

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

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