如何使用lambda表达式从XML文件中检索属性的值?

时间:2016-04-29 15:58:16

标签: linq

e.g。让我们说我想获得BranchName的价值

<repo>
  <Changeset  value="abcdefg"/>
  <BranchName value="gamma"/>
  <BuildNumber  value="1.2.3.4"/>
</repo>

我正在寻求的那种:

var doc = XDocument.Load(repoPath); 
var c = doc.Descendants("repo")..... Where(x=> x.Name == "changeset");

1 个答案:

答案 0 :(得分:0)

using System.Xml;
using System.Xml.Linq;
...
var c = doc.Descendants("repo")
           .Elements("Changeset") // getting "Changeset" nodes
           .Select(x => x.Attribute("value")) // getting "value" attribute
           .Where(a => a != null) // skip nulls (just in case)
           .Select(a => a.Value) // getting "value" attribute value
           .ToList();