Posted by: R Manimaran | March 20, 2011

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.

<?xml version="1.0" encoding="utf-8"?>
<Employees>
  <Employee Id="2" Name="Ram" />
  <Employee Id="5" Name="Rahul" />
  <Employee Id="8" Name="Manimaran" />
  <Employee Id="9" name="John" />
</Employees>

I want to get the max and min of the ID attribute.

XPath: MAX


XmlDocument doc = new XmlDocument();                     
doc.Load("../../Employees.xml");
XmlNode node = doc.SelectSingleNode("//Employees/Employee/@Id[not(. <=../preceding-sibling::Employee/@id) and not(. <=../following-sibling::Employee/@Id)]");
int maxId = Convert.ToInt32(node.Value);

XPath:MIN


XmlNode node1 = doc.SelectSingleNode("//Employees/Employee/@Id[not(. >=../preceding-sibling::Employee/@id) and not(. >=../following-sibling::Employee/@Id)]");
int minId = Convert.ToInt32(node1.Value);

The above can be obtained using System.Xml.Linq which available in Framework 3.5

LINQ: Max


XElement element = XElement.Load("../../Employees.xml");
int max = 
element.Elements("Employee").Max(l => int.Parse(l.Attribute("Id").Value));

LINQ: Min

int min =
element.Elements("Employee").Min(l => int.Parse(l.Attribute("Id").Value));

In the above XML we have find the max and min in the attributes value. Suppose if the xml is like this.I want to get the Max and Min value of the Age. How about here


<?xml version="1.0" encoding="utf-8"?>
<Persons>
  <Person Id="1">
    <Name>Mani</Name>
    <Age>27</Age>    
  </Person>
  <Person Id="2">
    <Name>Ram</Name>
    <Age>29</Age>
  </Person>
  <Person Id="3">
    <Name>Ela</Name>
    <Age>25</Age>
  </Person>
</Persons>

XPath: MAX


XmlNode person = doc.SelectSingleNode("//Person/Age[not(. <=../preceding-sibling::Person/Age) and not(. <=../following-sibling::Person/Age)]");
int ageMax = Convert.ToInt32(person.InnerText);

XPath: MIN


XmlNode person = doc.SelectSingleNode("//Person/Age[not(. >=../preceding-sibling::Person/Age) and not(. >=../following-sibling::Person/Age)]");
int ageMin = Convert.ToInt32(person.InnerText);

Using LINQ to get the Max and Min

LINQ: MAX


int maxAge = element.Elements("Person").Max(l=>int.Parse(l.Element("Age").Value));

LINQ: MIN


int minAge = 
element.Elements("Person").Min(m => int.Parse(m.Element("Age").Value));

Advertisements

Responses

  1. HI Manimaran,

    Thank you very much for your sample code on ‘XML – Find Max and Min Value in a Attribute using XPath and LINQ’. This is what I was looking for.

  2. hi,
    I am using xpath. I would like Employee ID max value and Employee Name. What should I do?

    • Hi,
      This is the way can follow. In a single statement we can’t get both. First find the max Id and with that fine the employee name.

      XmlNode employee = doc.SelectSingleNode(“//Employees/Employee[@Id='” + maxId+”‘]”);
      string EmployeeName = employee.Attributes[“name”].Value;

  3. great info. helped me a lot. thanks!
    hey, i clicked “votedown” by mistake on your last comment. sorry about that!

  4. Short, useful and correct – this is perfect. Thank you!

  5. Short and useful also for me, thank you!

  6. If one of the node as empty value how do you handle it.

    Example

    the code will fail in above scenario.

    • 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))]");

  7. 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));


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: