我正在用java编写代码并试图从这个URL解析xml: https ://maps.googleapis.com/maps/api/directions/xml?origin=30.606595,33.546753&destination=30.657406,33.712234&sensor=false
此 URL 属于 google API,它需要 2 个点(src,dest)并以 xml 形式返回它们之间的路由。
当我用eclipse调试程序时,它运行完美。但是当我在没有调试的情况下运行代码时,它会返回一个错误。(当我在函数末尾放置一个断点时,“dist”为空,我不知道为什么)知道为什么会这样吗?
代码是
public double calcDist(Point p) //p=the src of the ride (the dest in the calculation)
{
String src = Double.toString(this.lati);
src = src.concat(",");
src = src.concat(Double.toString(this.longi));
String dest = Double.toString(p.lati);
dest = dest.concat(",");
dest = dest.concat(Double.toString(p.longi));
String dist=null;
URL url = null;
try
{
url = new URL("https://maps.googleapis.com/maps/api/directions/xml?origin="+src+"&destination="+dest+"&sensor=false");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
db = dbf.newDocumentBuilder();
Document doc = null;
doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("leg");
for (int i = 0; i < nodeList.getLength(); i++)
{
Node node = nodeList.item(i);
NodeList nodeList2 =node.getChildNodes();
for (int j = 0; j < nodeList2.getLength(); j++)
{
Node child = nodeList2.item(j);
if (child.getNodeName().contentEquals("distance"))
{
NodeList nodeList3 = child.getChildNodes();
for (int p1 = 0; p1 < nodeList3.getLength(); p1++)
{
Node child2 = nodeList3.item(p1);
if (child2.getNodeName().contentEquals("text"))
{
Node tmp = child2.getFirstChild();
if (tmp != null)
dist = child2.getFirstChild().getNodeValue();
}
}
}
}
}
}
catch (ParserConfigurationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SAXException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
dist = dist.substring(0, dist.length()-3);
return Double.parseDouble(dist);
}