I find the existing answers too detailed and lengthy. Imagine what happens if you intend to make a selection based on multiple attributes?
The most compact and expressive solution at the same time is to use XPath extensions (from the System.Xml.XPath namespace).
For example, to get the state with id = 1 in India:
var xdoc = XDocument.Load(file); foreach (var element in xdoc.XPathSelectElements("//Country[@name='India']/state[@id=1]")) { Console.WriteLine("State " + element.Value + ", id " + (int)element.Attribute("id")); }
To get all conditions in all countries that have any identifier:
foreach (var element in xdoc.XPathSelectElements("//state[@id]")) { Console.WriteLine("State " + element.Value + ", id " + (int)element.Attribute("id")); }
Etc.
You can find the XPath specification here .
source share