使用SAX解析器或XmlPullParser解析GPX文件

3
我有许多GPX文件,它们是我的应用程序创建的,并且将在应用程序的后续阶段需要解析。通常我很难解析它们。我在此网站和其他网站上看到了许多解析器的示例,但它们都使用像TracksTrakcPoints这样的对象,但是这些类中包含的内容找不到。我真的很想能够仅解析该文件并将其分类为Location型的ArrayList。我还需要从文件中获取经度、纬度、时间和高程。

有人能帮我解决这个问题吗? 我不介意使用SAX parserXml pull parser或其他方法来完成它。


一个 gpx 文件可以有零个、一个或多个轨迹、路线或路标,因此 gpx 解析器具有这些类型的对象是有意义的。 Gpx 没有任何称为“位置”的东西。 您可以在规范中查看:http://www.topografix.com/GPX/1/1/ 您的文件是否完全是有效的 gpx 文件,还是您自己的 xml 格式? - Eddy
在这里我所说的是android.location,它实际上拥有GPX文件中的大部分属性,如经度、纬度、时间、海拔高度等。Android Location - Droid_Interceptor
3个回答

3

我想出来了,可能不是最优雅的方式,但它可以工作。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.location.Location;


public class GpxReader
{
private static final SimpleDateFormat gpxDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

public static List<Location> getPoints(File gpxFile)
{
    List<Location> points = null;
    try
    {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();

        FileInputStream fis = new FileInputStream(gpxFile);
        Document dom = builder.parse(fis);
        Element root = dom.getDocumentElement();
        NodeList items = root.getElementsByTagName("trkpt");

        points = new ArrayList<Location>();

        for(int j = 0; j < items.getLength(); j++)
        {
            Node item = items.item(j);
            NamedNodeMap attrs = item.getAttributes();
            NodeList props = item.getChildNodes();

            Location pt = new Location("test");

            pt.setLatitude(Double.parseDouble(attrs.getNamedItem("lat").getTextContent()));
            pt.setLongitude(Double.parseDouble(attrs.getNamedItem("lon").getTextContent()));

            for(int k = 0; k<props.getLength(); k++)
            {
                Node item2 = props.item(k);
                String name = item2.getNodeName();
                if(!name.equalsIgnoreCase("time")) continue;
                try
                {
                    pt.setTime((getDateFormatter().parse(item2.getFirstChild().getNodeValue())).getTime());
                }

                catch(ParseException ex)
                {
                    ex.printStackTrace();
                }
            }

            for(int y = 0; y<props.getLength(); y++)
            {
                Node item3 = props.item(y);
                String name = item3.getNodeName();
                if(!name.equalsIgnoreCase("ele")) continue;
                pt.setAltitude(Double.parseDouble(item3.getFirstChild().getNodeValue()));
            }

            points.add(pt);

        }

        fis.close();
    }

    catch(FileNotFoundException e)
    {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    catch(ParserConfigurationException ex)
    {

    }

    catch (SAXException ex) {
    }

    return points;
}

public static SimpleDateFormat getDateFormatter()
  {
    return (SimpleDateFormat)gpxDate.clone();
  }

}

希望这能帮助一些人。

1
使用SAX:
GpxImportActivity.java
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;

public class GpxImportActivity extends Activity {
private String fileName ="gpsTrack.gpx";
private File sdCard;
private List<Location> locationList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gpx_import);

    locationList = new ArrayList<Location>();

    sdCard = Environment.getExternalStorageDirectory();     
    if (!sdCard.exists() || !sdCard.canRead()) {
        Log.d("GpxImportActivity", "SD-Card not available or not readable");
        finish();
    }
    boolean availableFile = new File(sdCard, fileName).exists();
    if (!availableFile) {
        Log.d("GpxImportActivity", "File \"" +fileName+ "\" not available");
        finish();
    } else {
        Log.d("GpxImportActivity", "File \"" +fileName+ "\" found");
    }

    try {
    System.setProperty("org.xml.sax.driver","org.xmlpull.v1.sax2.Driver");
    XMLReader xmlReader = XMLReaderFactory.createXMLReader();
    /*
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    spf.setValidating(false);
    SAXParser saxParser = spf.newSAXParser();
    XMLReader xmlReader = saxParser.getXMLReader();
    */      
    GpxFileContentHandler gpxFileContentHandler = new GpxFileContentHandler();
    xmlReader.setContentHandler(gpxFileContentHandler);

    FileReader fileReader = new FileReader(new File(sdCard,fileName));
    InputSource inputSource = new InputSource(fileReader);          
    xmlReader.parse(inputSource);

    locationList = gpxFileContentHandler.getLocationList(); 

    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.gpx_import, menu);
    return true;
    }
}

GpxFileContentHandler.java

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;

import android.location.Location;

public class GpxFileContentHandler implements ContentHandler {
    private String currentValue;
    private Location location;
    private List<Location> locationList;
    private final SimpleDateFormat GPXTIME_SIMPLEDATEFORMAT = new SimpleDateFormat(
        "yyyy-MM-dd'T'HH:mm:ss'Z'");

    public GpxFileContentHandler() {
        locationList = new ArrayList<Location>();
    }

    public List<Location> getLocationList() {
        return locationList;
    }

    @Override
    public void startElement(String uri, String localName, String qName,
        Attributes atts) throws SAXException {

        if (localName.equalsIgnoreCase("trkpt")) {
            location = new Location("gpxImport");
            location.setLatitude(Double.parseDouble(atts.getValue("lat").trim()));
            location.setLongitude(Double.parseDouble(atts.getValue("lon").trim()));
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName)
        throws SAXException {
        if (localName.equalsIgnoreCase("ele")) {
            location.setAltitude(Double.parseDouble(currentValue.trim()));
        }

        if (localName.equalsIgnoreCase("time")) {
            try {
            Date date = GPXTIME_SIMPLEDATEFORMAT.parse(currentValue.trim());
            Long time = date.getTime();
            location.setTime(time);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        if (localName.equalsIgnoreCase("trkpt")) {
            locationList.add(location);
        }
    }

    @Override
    public void characters(char[] ch, int start, int length)
        throws SAXException {
        currentValue = new String(ch, start, length);
    }

    @Override
    public void startDocument() throws SAXException {
        // TODO Auto-generated method stub
    }

    @Override
    public void endDocument() throws SAXException {
        // TODO Auto-generated method stub
    }

    @Override
    public void endPrefixMapping(String prefix) throws SAXException {
        // TODO Auto-generated method stub
    }

    @Override
    public void ignorableWhitespace(char[] ch, int start, int length)
        throws SAXException {
        // TODO Auto-generated method stub
    }

    @Override
    public void processingInstruction(String target, String data)
        throws SAXException {
        // TODO Auto-generated method stub
    }

    @Override
    public void setDocumentLocator(Locator locator) {
        // TODO Auto-generated method stub
    }

    @Override
    public void skippedEntity(String name) throws SAXException {
        // TODO Auto-generated method stub
    }

    @Override
        public void startPrefixMapping(String prefix, String uri)
            throws SAXException {
            // TODO Auto-generated method stub
    }

}

0

可以立即使用、开源、完全功能的 Java GpxParser(还有更多)在这里 https://sourceforge.net/projects/geokarambola/

详细信息在这里 https://plus.google.com/u/0/communities/110606810455751902142

使用上述库解析 GPX 文件只需要一行代码:

Gpx gpx = GpxFileIo.parseIn( "SomeGeoCollection.gpx" ) ;

获取其点、路线或轨迹也很简单:

ArrayList<Route> routes = gpx.getRoutes( ) ;
Route route = routes.get(0) ; // First route.

然后您可以迭代路线点并直接获取它们的纬度/经度/高程

for(RoutePoint rtePt: route.getRoutePoints( ))
  Location loc = new Location( rtePt.getLatitude( ), rtePt.getLongitude( ) ) ;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接