First, we need an XML document with some data in it. For this purpose, I have already created an XML document with few records in it. You can open library.xml document to view it. Copy the contents of the file and save it in your computer and name it as library.xml, because I am using the same file name in my example. You can change the name of the file according to your choice later.
We are particularly interested in the Price attribute. Because, this attribute has numeric values and decimals. The child node List in the XML document has many sub-child nodes called the Price and we want the Max and Min values (only) separated from the rest.
<html> <body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <p> <input type="button" id="bt" value="Get Min and Max value in XML" /> </p> <p id="details"></p> </body> <script> $(document).ready(function () { $('#bt').click(function () { $.ajax({ type: 'GET', url: '../../library/library.xml', dataType: 'xml', success: function (xmlData) { // GET MAX PRICE. var maxPrice = 0; $(xmlData).find('List').each(function () { var BookPrice = parseFloat($(this).find('Price').text()); maxPrice = (BookPrice >= maxPrice) ? BookPrice : maxPrice; }); $('#details').append('Maximum Price: <b>' + maxPrice + '</b><br />'); // GET MIN PRICE. var minPrice = maxPrice; $(xmlData).find('List').each(function () { var BookPrice = parseFloat($(this).find('Price').text()); minPrice = (BookPrice <= minPrice) ? BookPrice : minPrice; }); $('#details').append('Minimum Price: <b>' + minPrice + '</b>'); } }); }); }); </script> </html>
Using Ajax, we will first Get the XML document when the page loads and becomes ready for manipulation. If the operation is a success, we are ready to pull out the data from the XML. We are using jQuery .find() method to look for values inside the List attribute. Next, using the same method, we will get values from the Price attributes.
var BookPrice = parseFloat($(this).find('Price').text());
The algorithm for getting the Maximum and Minimum price is rather simple. First, we will get the Max value. Later, using the result of the Max value, get the Min value. In both the blocks, I am using a ternary operator, which will return a value based on a condition. If the condition is true, we get our value.
That is it.
Was it useful? If you know any trick using similar procedures, then please do not hesitate to share it with us here in this blog. Send me your tip, I’ll publish it here and also make sure that your tip is viewed by thousands. In addition, you can leave a message below.