使用LINQ读取XML数据,多个具有相同名称的元素 [英] Reading XML data using LINQ, multiple elements with the same name
问题描述
Visual Studio 2010,Silverlight 4和C#.我将以下数据存储在XML文件中:
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>
这是我当前的代码.
XDocument xmlDoc = XDocument.Load("XMLDocument.xml");
var ElementsList = from Elements in xmlDoc.Descendants("root")
select new
{
ElementContent = Elements.Element("Element").Value,
};
此代码仅将第一个元素放在列表中,而将所有其他元素都排除在外.如何重写此代码,以便捕获XML文件中所有名为元素"的元素?
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?
推荐答案
这可以做到:
XDocument xmlDoc = XDocument.Load("XMLDocument.xml");
var ElementsList = from Elements in xmlDoc.Descendants("element")
select new
{
ElementContent = Elements.Value
};
或更简单的点表示法:
var ElementsList = xmlDoc.Descendants("element")
.Select(x => new { ElementContent = x.Value });
但是请注意,此后您只有一个元素枚举,如果您想要一个列表(如变量名所示),则可以在Select之后添加.ToList()
:
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();
此列表将包含3个元素(基于您的示例XML.
)(具有ElementContent
属性的匿名类型).如果您不需要该属性(我想您不需要),那么这是一个简化版本,只返回字符串列表:
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();
这篇关于使用LINQ读取XML数据,多个具有相同名称的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!