Photo
XJ

XJ Sample Program

Totals.xj performs a simple data processing job. It works on a schema, salesschema.xsd, describing sales per each year of interest, and within each year, per each region of interest. The document element is salesdata. It contains a sequence of year elements. A year element contains the year (element theyear). In addition, it contains a sequence of region elements. A region element, in turn, contains the name of the region (element name) and the sales in this region (element sales). For example, chart.xml is a sample document conforming to the schema.

The program Totals.xj that operates on this data is provided below. Hover your mouse over any line to get additional description. If you'd rather see a fully annotated version, click here. [Multiline tooltips do not work yet in some browsers.]

package com.ibm.xj.samples.totals;

import java.io.IOException;
import java.io.FileInputStream;

import com.ibm.xj.samples.totals.salesschema.*;

public class Totals {
    private salesdata document;

    public static void main(String[] argv) {
        if (argv.length != 1) {
            System.err.println("Usage: Totals <filename>");
            System.exit(-1);
        }
        Totals t = new Totals();
        t.doParse(argv[0]);
        t.doExecute();
    }

    public void doParse(String filename) {
        try {
            document = new salesdata(new FileInputStream(filename));
        }
        catch (java.io.IOException e) {
            throw new Error("Cannot parse input file");
        }
    }

    public void doExecute() {
        computeSales(document);
    }

    private static void computeSales(salesdata sd) {
        int min = 70;
        System.out.println("Total Sales");
        int grandTotal = 0;
        Sequence<year> ys = sd[|/year[sum(.//sales) > $min]|];
        if (ys.isEmpty())
            System.out.println("No elements matched");

        XMLCursor<year> y = ys.iterator();   
        while (y.hasNext()) {
            year ytmp = y.next();
            String str = ytmp[|/theyear|];
            System.out.print(str + "\t");
            int total = 0;
            XMLCursor<sales> s = ytmp[|//sales|].iterator();
            while (s.hasNext()) {
                sales stmp =  s.next();
                total = total + stmp;
            }
            grandTotal += total;
            System.out.println(total);
        }
        double conversionFactor = 1.8;
        sales s2 = new sales(<sales unit="GBP">{conversionFactor * grandTotal}</sales>);
        XMLDocumentOutputStream out = new XMLDocumentOutputStream(System.out);
        out.println(s2);

        System.out.println("Grand Total: " + grandTotal);
    }
}