I have the following xml. Given, a UID, Manufacturer Name and Image Layout, I want to pull out all possible sizes that exist in the xml.
<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>
The way i do it right now is:
XElement rules = XElement.Parse(xmlDoc.OuterXml);
var uids = rules.Elements("UniqueID")
.Where(x=> (string)x.Attribute("UID")=="123413")
.ToList();
foreach(var uid in uids)
{
var manufacturers = uid.Elements(("UniqueID")
.Where(x=> (string)x.Attribute("Name")=="XYZ Company")
.ToList();
}
and so on until I have a collection of the possible sizes.
So I am using 3 foreach loops. Is there a better way acheive this with probably one line of code, using LINQ?
It’s a little bit of a mouthful, but you can use XPathSelectElements:
Obviously, you could use string formatting to dynamically insert values for @UID and @Name.
Make sure to include
System.Xml.XPath.