You can use XPath queries and LINQ for XML.
Here is an example XPath. First you need to prepare your XML, for this you can use Stream objects, transfer to the URI constructor, or use the simplest XMLReader. In this case, for the sake of completeness, a MemoryStream is used, for the rest, see the description of XDocument.Load .
string xml = @"<?xml version=""1.0"" encoding=""utf-8""?> <users> <user name=""Bill Gates"" group=""programmers""> <company>Microsoft</company> <age>48</age> </user> <user name=""Larry Page"" group=""programmers""> <company>Google</company> <age>42</age> </user> <user name=""Edward Norton"" single=""actor""> <company>NewLineCinema</company> <age>40</age> </user> </users> "; MemoryStream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)); XDocument xdoc = XDocument.Load(xmlStream);
After the document is loaded, you can easily read the data using XPath queries. They can be quite flexible and complex, allowing you to handle multiple conditions in one line. Of the minuses, you'll have to learn XPath.
var programmers = xdoc.Document.XPathSelectElements(@"./users/user[@group=""programmers""]"); var single = xdoc.Document.XPathSelectElements(@"./users/user[@single]"); var result = programmers.Count() > 0 ? programmers : single;
UPD: sample data output to the console
foreach (var res in result) { Console.WriteLine(""); Console.WriteLine(res.Element("company").Value); Console.WriteLine(res.Element("age").Value); Console.WriteLine(res.Attribute("name") != null ? res.Attribute("name").Value : ""); Console.WriteLine(res.Attribute("group") != null ? res.Attribute("group").Value : ""); }