Accepted answer

It's a little bit of a mouthful, but you can use XPathSelectElements:

 var sizes = rules.XPathSelectElements("//UniqueId[@UID = '123413']/Manufacturer[@Name = 'XYZ Company']//Size");

Obviously, you could use string formatting to dynamically insert values for @UID and @Name.

Make sure to include System.Xml.XPath.


I like James's XPath approach. Here is what it might look like if you just keep stacking LINQ.

var sizes = xmlDoc.Elements("Rules")
    .Where(e => e.Attribute("UID").Value=="123413")
    .Where(e => e.Attribute("Name").Value=="XYZ Company")
    .Where(e => e.Attribute("Layout").Value=="Portrait")

sizes ends up being IEnumerable (2 items)

<Size rows="512" cols="512" price="x" />
<Size rows="1024" cols="1024" price="y" />


Try this(used XPath):

String xmlString = @"<Rules> <UniqueID UID=""123413""> <Manufacturer Name=""XYZ Company""> <Image Layout=""Portrait""> <Size rows=""512"" cols=""512"" price=""x"" /> <Size rows=""1024"" cols=""1024"" price=""y"" /> </Image> </Manufacturer> </UniqueID> </Rules>";
XElement element = XElement.Parse(xmlString);

var uids = element.XPathSelectElements("//UniqueID[@UID=123413]/Manufacturer[@Name='XYZ Company']/Image[@Layout='Portrait']/Size")
          .Select(a=> new {rows=a.Attribute("rows").Value, cols=a.Attribute("cols").Value})
foreach(var uid in uids) 
    Console.WriteLine(uid.rows + " - " + uid.cols);

Related Articles