因此,假设您拥有以下XML结构。
<Class>
<Students>
<Student>
<StudentNo>555</StudentNo>
<Firstname>Joe</Firstname>
<Lastname>Smith</Lastname>
</Student>
<Student>
<StudentNo>222</StudentNo>
<Firstname>Smith</Firstname>
<Lastname>Joe</Lastname>
</Student>
<Students>
</Class>
并且您希望使用linq获取所有的Firstnames和lastnames。现在我得到以下
foreach (XElement x in data.Descendants("Student").SelectMany(e => data.Descendants("Firstname")))
{
Console.WriteLine(x.Value);
}
但我怎么能得到lastName呢?
答案 0 :(得分:5)
您可以使用匿名类型执行此操作:
var query=data.Descendants("Student")
.Select(s=> new { FirstName=s.Element("FirstName").Value,
LastName=s.Element("Lastname").Value});
或者您可以创建自定义类并保存结果:
var query=data.Descendants("Student")
.Select(s=> new Student{ FirstName=s.Element("FirstName").Value,
LastName=s.Element("Lastname").Value});
答案 1 :(得分:1)
您可以这样写:
var firstnames = data.Descendants("Student").Select(x => x.Firstname);
var lastnames = data.Descendants("Student").Select(x => x.Lastname);
或者
var firstAndLastnames = data.Descendants("Student").Select(x => new { Firstname = x.Firstname, Lastname = x.Lastname });