I want to select the node whose identifier is "abc" a...">

Use LINQ in XmlNodeList

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

I want to select the node whose identifier is "abc" and return it 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 not work, node ["id"]. InnerText is always "". Can you indicate where the problem is?

Thank you so much

+15
c # xml linq
source share
3 answers

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

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

+6
source share

In addition to the fact that your code fragment will not be compiled due to the non-unique node variable (first outside the linq query, and then in the where lambda method), you also missed Attributes in your request.

It should be something like

 var node = list.Cast<XmlNode>() .Where(n => n.Attributes["id"].InnerText == "abc") .Select(x => x.Attributes["abv"].InnerText); 
+17
source share

Just cast the XmlNodeList to a list, like this:

  List<XmlNode> list = new List<XmlNode>(); foreach(XmlNode a in xmlNodeList) { list.Add(a); } list.OrderBy((element) => element.ChildNodes[0].InnerText); 
0
source share

All Articles