Save those precious 5000 statements and use xpath!

Save those precious 5000 statements and use xpath!

In the past I used to loop over XML using the toXmlList() function combined with some if statements...

PROBLEM: Each iteration adds to your # of statements used and it's slow. 

There's a better way! Use xpath to it's fullest and let xpath do the heavy lifting.. Here's a function that let's you pass a "filter" map to your xml. It iterates over a map's keys and then builds up an xpath statement. Once the xpath statement string is built up it filters ALL your xml nodes (based on your xpath prefix change that part how you see fit). ALSO, you can pass an operator of either "and" or "or". 

This is the first version of this script. Later add a way to set an operator for each value in the filter map.. 

  1. string xml.filter(str xmlStr, string operator, map filter)
  2. {
  3. /**
  4. * return string so that you can use the xml in a different function. You can't return xml
  5. *@param xmlStr your xml formatted string
  6. *@param operator either "and" or "or" for now can't be both 
  7. *@param added to the xpath to filter your records
  8. */

  9. //convert to xml
  10.     xml = data.toXML();

  11.   //get the keys for your filterMap
  12.     keys = input.filter.keys();
  13.     
  14. //start your xpath NOTE: the "[" is important we use this for our filter params
  15.      xpath = "/root/record[";
  16.    
  17. //loop through the keys and build up your xpath. prints like this "/root/record[key=value and key=value]"
  18.  for each key in keys
  19.     {
  20.         xpath = (xpath + " " + key + "=" + "'" + input.filter.get(key) + "' "+operator;
  21.     }
  22.     xpath = xpath + "]";
  23. //remove last operator from bracket
  24.     xpath = (xpath).replaceAll(operator+"]","]");
  25.     //records
  26.     filterRecords = xml.executeXPath(xpath);
  27. //return xml formatted string
  28.     return filterRecords.toString();
  29. }