giovedì 26 gennaio 2012

Java - How to parse GPX files

Parse GPX files in Java with ximpleware lib:




package readgpxfile;

import com.ximpleware.AutoPilot;
import com.ximpleware.NavException;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
import com.ximpleware.XPathEvalException;
import com.ximpleware.XPathParseException;

/**
 * @author Marco Berri marcoberri@gmail.com 
 * @see http://tecnicume.blogspot.com
 */
public class ReadGpxFile {

    /**
     * @param args the command line arguments
     * @throws XPathEvalException
     * @throws NavException  
     */
    public static void main(String[] args) throws XPathEvalException, NavException {


        VTDGen vg = new VTDGen();
        vg.parseFile("/Users/marco/Desktop/test.gpx", true);

        System.out.println("Start");


        AutoPilot ap;
        VTDNav vn = vg.getNav();


        try {
            vn.toElement(VTDNav.ROOT);
            vn.matchElement("gpx");
            ap = new AutoPilot(vn);
            ap.selectXPath("/gpx/trk/trkseg/*");

        } catch (XPathParseException ex) {
            System.out.println(ex.getMessage());
            return;
        } catch (NavException ex) {
            System.out.println(ex.getMessage());
            return;
        }

        int r = 0;
        while ((r = ap.evalXPath()) != -1) {


            if (vn.toString(r).equals("trkpt")) {
                System.out.println("lat:" + vn.getAttrVal("lat"));
                System.out.println("lon:" + vn.getAttrVal("lon"));

                VTDNav vntrkp = vn.cloneNav();

                if (vntrkp.toElement(VTDNav.FC)) {

                    do {


                        if (vntrkp.toString(vntrkp.getCurrentIndex()).equals("ele")) {
                            System.out.println("ele:" + vntrkp.toString(vntrkp.getText()));
                        } else if (vntrkp.toString(vntrkp.getCurrentIndex()).equals("fix")) {
                            System.out.println("fix:" + vntrkp.toString(vntrkp.getText()));
                        } else if (vntrkp.toString(vntrkp.getCurrentIndex()).equals("sat")) {
                            System.out.println("sat:" + vntrkp.toString(vntrkp.getText()));
                        } else if (vntrkp.toString(vntrkp.getCurrentIndex()).equals("time")) {
                            System.out.println("time:" + vntrkp.toString(vntrkp.getText()));
                        }

                    } while (vntrkp.toElement(VTDNav.NEXT_SIBLING));

                }


            }
        }

    }
}


Nessun commento: