Search code examples
c#.netxmllinq

use LINQ on XmlNodeList


<X version="1.0">
  <Y id="abc" abv="a"/>
  <Y id="edf" abv="e"/>
</X>

I want to select the node whose id is "abc", and return its abv "a".

XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlNodeList list = doc.SelectNodes("X/Y");
var node = list.Cast<XmlNode>().Where(node => node["id"].InnerText == "abc")
                               .Select(x=>x["abv"].InnerText);

But it does't work, node["id"].InnerText is always "". Can you point out where is a problem?

Thanks a lot


Solution

  • The InnerText for a node is the text that appears between <node> and </node>. So for, eg <Y attributes /> there is no inner text.

    You need to use node => node.Attributes["id"].Value == "abc"