XML – Find Max and Min Value in a Attribute using XPath and LINQ

XML – Find Max and Min Value in a Attribute using XPath and LINQ

I had worked in projects where I have used XML as a Data Source. I used to use XPath to parse and traverse the XML Document. Here is a sample XML file which I used to find the max and min of an attribute value.

Hi Vivek,
Good Question. In XPath we have a function to trim the empty value. Here is the XPath Query
XPath:
XmlNode node = doc.SelectSingleNode(“//Employees/Employee/@Id[(normalize-space(.)!=” and not(normalize-space(.) <=../preceding-sibling::Employee/@id)) and (normalize-space(.) !='' and not(normalize-space(.) <=../following-sibling::Employee/@Id))]");

To handle empty string in the nodes in Linq we can use as below
int max =element.Elements(“Employee”).Where(l=>l.Attribute(“Id”).Value.Trim()!=string.Empty).Max(t => int.Parse(t.Attribute(“Id”).Value));