To XML
BeanShell is a small, free, embeddable Java source interpreter with object scripting language features,
written in Java. BeanShell is a natural scripting language for Java.
This requires the library bsh-2.0b4.jar to be in classpath.
The following example shows generating an XML from beanshell script.
sb = new StringBuilder () ;
sb.append ( "<Students>" ) ;
for ( std : students ) {
sb.append ( "<Student>" ) ;
sb.append ( "<Name>" ) .append ( std.name ) .append ( "</Name>" ) ;
sb.append ( "<Age>" ) .append ( std.age ) .append ( "</Age>" ) ;
sb.append ( "</Student>" ) ;
}
sb.append ( "</Students>" ) ;
print ( sb ) ;
package com.bethecoder.tutorials.bean_shell.common;
public class Student {
private String name;
private int age;
private String hobby;
public Student () {
}
public Student ( String name, int age, String hobby ) {
super () ;
this .name = name;
this .age = age;
this .hobby = hobby;
}
public String getName () {
return name;
}
public void setName ( String name ) {
this .name = name;
}
public int getAge () {
return age;
}
public void setAge ( int age ) {
this .age = age;
}
public String getHobby () {
return hobby;
}
public void setHobby ( String hobby ) {
this .hobby = hobby;
}
public boolean isKid () {
return age < 5 ;
}
public String toString () {
return "Student[name = " + name + ", age = " + age + ", hobby = " + hobby + "]" ;
}
}
package com.bethecoder.tutorials.bean_shell;
import java.io.InputStreamReader;
import java.util.Arrays;
import bsh.EvalError;
import bsh.Interpreter;
import com.bethecoder.tutorials.bean_shell.common.Student;
public class ToXMLTest {
/**
* @param args
* @throws EvalError
*/
public static void main ( String [] args ) throws EvalError {
Student student = new Student ( "Sriram" , 2 , "Chess" ) ;
Student student2 = new Student ( "Sudhakar" , 29 , "Painting" ) ;
Student student3 = new Student ( "Charan" , 18 , "Reading books" ) ;
Interpreter interpreter = new Interpreter () ;
interpreter.set ( "students" , Arrays.asList ( student, student2, student3 )) ;
InputStreamReader reader = new InputStreamReader (
ToXMLTest. class .getClassLoader ()
.getResourceAsStream ( "toxml.bsh" )) ;
interpreter.eval ( reader ) ;
}
}
It gives the following output,