【问题标题】:Parsing GPX files with SAX parser or XmlPullParser使用 SAX 解析器或 XmlPullParser 解析 GPX 文件
【发布时间】:2012-03-14 02:27:52
【问题描述】:

我的应用程序创建了许多 gpx 文件,这些文件需要在应用程序的稍后阶段进行解析。 我一般无法解析它们。我在这个站点和其他站点上看到了很多解析器示例,但它们都使用 TracksTrakcPoints 之类的对象,但找不到这些类包含的内容。我真的希望能够解析文件并将其分类为ArrayListLocation。我需要从文件中获取经纬度以及时间和海拔。

有人可以帮我解决这个问题吗? 我不介意使用SAX parserXml pull parser 或其他方法。

【问题讨论】:

  • 一个 gpx 文件有零个、一个或多个轨道、路线或航路点,因此 gpx 解析器具有这些类型的对象是有意义的。 Gpx 没有任何称为“位置”的东西。您可以查看规格:topografix.com/GPX/1/1您的文件是有效的 gpx 还是您自己的 xml 格式?
  • 在我正在考虑的位置中,android.location 实际上具有 gpx 文件中的大部分属性 long、lat、time、elevation、time 等。Android Location

标签: android gpx


【解决方案1】:

想出来了,可能不是最优雅的方法,但它确实有效

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();
  }

}

希望对大家有所帮助

【讨论】:

    【解决方案2】:

    使用 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
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      即用型、开源且功能齐全的 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( ) ) ;
      

      【讨论】:

        猜你喜欢
        • 2012-01-28
        • 2012-02-12
        • 1970-01-01
        • 2011-02-28
        • 2012-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-30
        相关资源
        最近更新 更多