Wiki

Clone wiki

symja_android_library / examples / MathML

MathML example

Here is an example for converting a Mathematica like syntax math expression to a MathML snippet:

Example:

import java.io.StringWriter;
import org.matheclipse.core.basic.Config;
import org.matheclipse.core.eval.EvalEngine;
import org.matheclipse.core.eval.MathMLUtilities;
import org.matheclipse.parser.client.SyntaxError;
import org.matheclipse.parser.client.math.MathException;

public class MathMLExample { 
	public static void main(String[] args) {
		try { 
			// false -> distinguish between upper- and lowercase identifiers:
			Config.PARSER_USE_LOWERCASE_SYMBOLS = false;
			// false -> switch to Mathematica syntax mode:
			EvalEngine engine = new EvalEngine(false);
			// don't use m: prefix for mathml tags / don't print MathML header information
			MathMLUtilities mathUtil = new MathMLUtilities(engine, false, false);

			StringWriter stw = new StringWriter();
			mathUtil.toMathML("Sum[i, {i,1,n}]", stw);
			// print: <math><mrow><munderover><mo>&#x2211;</mo><mrow><mi>i</mi><mo>=</mo><mn>1</mn></mrow><mi>n</mi></munderover><mi>i</mi></mrow></math> 
			System.out.println(stw.toString());
			
			 stw = new StringWriter();
			mathUtil.toMathML("MatrixForm[{{a,b},{c,d}}]", stw);
			// print: <math><mrow><mo>(</mo><mtable><mtr><mtd><mi>a</mi></mtd><mtd><mi>b</mi></mtd></mtr><mtr><mtd><mi>c</mi></mtd><mtd><mi>d</mi></mtd></mtr></mtable><mo>)</mo></mrow></math>
			System.out.println(stw.toString());
		} catch (SyntaxError e) {
			// catch Symja parser errors here
			System.out.println(e.getMessage());
		} catch (MathException me) {
			// catch Symja math errors here
			System.out.println(me.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

GIT: MathML examples:

Updated