maandag 11 augustus 2014

From String to calculation

Introduction:

After the marshalling drill I have been thinking about how can we do small changes in xml without marshalling. The only other option I could come up with is xpath queries combined with element value changes. For primitive type changes this is a good idea but what if someone needs some complex calculations with a value from the xml file. Even this can be done.

The solution:

What I could think of was some kind of calculation template in a String something


//The numbers to calculate.
        int number1 = 40;
        int number2 = 2;

//Creating the javascript engine
        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("JavaScript");

//The calculation template can be more complex
        String calcuationTemplate = "%d * %d";
        calcuationTemplate = String.format(calcuationTemplate, number1,number2);
        try {
//The actual calculation
            System.out.println(engine.eval(calcuationTemplate));
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }

The conclusion:

After some googling and trying I found that yet again this is pretty simple. With this I can do as much math I like in a very simple way. The only thing I still have to take care of is a difference between the numbers that have been given and the numbers that are retrieved from the xml file.

have fun!

Geen opmerkingen:

Een reactie posten