我有一些我的应用程序创建的 gpx 文件,需要在应用程序的稍后阶段进行解析。
我一般无法解析它们。我在这个网站和其他网站上看到了很多解析器的例子,但它们都使用像 Tracks
和 TrakcPoints
这样的对象,但是找不到这些类包含的内容。我真的很想能够解析文件并将其分类到 Location
的 ArrayList
中。我需要从文件中获取经度和纬度以及时间和海拔。
有人可以帮我解决这个问题吗?
我不介意使用 SAX 解析器
或 Xml pull 解析器
或其他方法。
最佳答案
想通了,可能不是最优雅的方式,但它有效
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();
}
}
希望这对一些人有帮助
关于android - 使用 SAX 解析器或 XmlPullParser 解析 GPX 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9417189/