XML 位于http://www.opencellid.org/cell/get?key=myapikey&mcc=250&mnc=99&cellid=29513&lac=0
<rsp stat="ok">
<cell mnc="45" nbSamples="3" lac="10113" mcc="404" lat="12.9929332248439" cellId="13113" range="6000" lon="77.5656492910538"/>
</rsp>
我正在尝试读取属性lat和lon的值。
这是在我的 MainActivity 中:
try {
URL url = new URL(
"http://www.opencellid.org/cell/get?key=myapikey&mcc=250&mnc=99&cellid=29513&lac=0");
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
SAXHandler mySAXHandler = new SAXHandler();
xr.setContentHandler(mySAXHandler);
xr.parse(new InputSource(url.openStream()));
Log.i("msg", "success");
} catch (Exception e) {
Log.i("msg", "fail");
}
这是 SAXHandler 类:
public class SAXHandler extends DefaultHandler {
private ParsedXMLDataSet myParsedXMLDataSet = new ParsedXMLDataSet();
public ParsedXMLDataSet getParsedData() {
return this.myParsedXMLDataSet;
}
@Override
public void startDocument() throws SAXException {
this.myParsedXMLDataSet = new ParsedXMLDataSet();
}
@Override
public void endDocument() throws SAXException {
}
@Override
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
if (localName.equals("rsp")) {
if (localName.equals("cell")) {
String attrValue1 = atts.getValue("lat");
String attrValue2 = atts.getValue("lon");
myParsedXMLDataSet.setExtractedString(attrValue1,
attrValue2);
}
}
}
@Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("rsp")) {
if (localName.equals("cell")) {
}
}
}
}
这是 ParsedXMLDataSet 类:
public class ParsedXMLDataSet {
private String lat = null, lon = null;
public void setExtractedString(String a, String b) {
this.lat = a;
this.lon = b;
}
public String toString() {
return "Latitude = " + this.lat + "Longitude = " + this.lon;
}
}
我无法弄清楚出了什么问题。我在 Logcat 中看到的只是“失败”。e.getMessage() 为空白。