In this artilce we will discuss how to get Max, Min, Sum and Average of any element in XML using Linq.

Let's see how we can do this.
Step 1: Create a xml name ProductInfo.xml like below structure.
< Products> <Product id='1'> <Quantity>4</Quantity> <Price>100</Price> </Product> <Product
id='2'> <Quantity>5</Quantity> <Price>400</Price> </Product> <Product id='3'> <Quantity>6</Quantity> <Price>600</Price> </Product> <Product id='4'> <Quantity
>9</Quantity> <Price>700</Price> </Product> <Product id='5'> <Quantity>4</Quantity> <
Price>800</Price> </Product> <Product id='6'> <Quantity>2</Quantity> <Price>100</Price> </Product> </Products> Get Min Value: Write below code to get minimum price of any product from above XML
string strFileName = Server.MapPath("ProductInfo.xml"); XDocument xmlDoc = XDocument.Load(strFileName); var xmlValue = (from prod in xmlDoc.Descendants("Product") select ( int.Parse(prod.Element("Price").Value) )).Min();
Get Max Value: Write below code to get maximum price of any product from above XML
string strFileName = Server.MapPath("ProductInfo.xml"); XDocument xmlDoc = XDocument.Load(strFileName); var xmlValue = (from prod in xmlDoc.Descendants("Product") select ( int.Parse(prod.Element("Price").Value) )).Max();
Get Sum: Write below code to get sum of price of all products from above XML
string strFileName = Server.MapPath("ProductInfo.xml"); XDocument xmlDoc = XDocument.Load(strFileName); var xmlValue = (from prod in xmlDoc.Descendants("Product") select ( int.Parse(prod.Element("Price").Value) )).Sum();
Get Average: Write below code to get average price of products from above XML
string strFileName = Server.MapPath("ProductInfo.xml"); XDocument xmlDoc = XDocument.Load(strFileName); var xmlValue = (from prod in xmlDoc.Descendants("Product") select ( int.Parse(prod.Element("Price").Value) )).Average(); Live Demo
|