Android应用中如何获取XML里index=1的ReportBody内geopoint值
Hey there! You’ve already nailed the part of fetching the XML content via AsyncTask—great job! Now let’s get that geopoint value from the ReportBody node where index="1".
I’ll show you two common ways to parse the XML in Android, starting with the XmlPullParser (Android’s native, memory-efficient parser) since it’s ideal for mobile apps.
Method 1: Using XmlPullParser
First, add a helper method to parse the XML string and extract the target geopoint. Then, we’ll update your AsyncTask to handle the parsing after fetching the XML.
Step 1: Add the XML Parsing Method
Add this method inside your MainActivity class:
private String extractGeopointFromXml(String xmlContent) throws XmlPullParserException, IOException { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser parser = factory.newPullParser(); parser.setInput(new StringReader(xmlContent)); int eventType = parser.getEventType(); int reportBodyIndex = 0; boolean isTargetReportBody = false; String geopointValue = null; while (eventType != XmlPullParser.END_DOCUMENT) { String tagName = parser.getName(); switch (eventType) { case XmlPullParser.START_TAG: if ("ReportBody".equals(tagName)) { // Get the index attribute value String indexAttr = parser.getAttributeValue(null, "index"); if ("1".equals(indexAttr)) { reportBodyIndex = 1; isTargetReportBody = true; } else { reportBodyIndex = Integer.parseInt(indexAttr); isTargetReportBody = false; } } // Once we're inside the target ReportBody, look for geopoint tag if (isTargetReportBody && "geopoint".equals(tagName)) { // Get the text inside the geopoint tag geopointValue = parser.nextText(); // We found what we need, can break early to save resources break; } break; case XmlPullParser.END_TAG: if ("ReportBody".equals(tagName) && reportBodyIndex == 1) { isTargetReportBody = false; } break; default: break; } eventType = parser.next(); } return geopointValue; }
Step 2: Update Your AsyncTask
Your original AsyncTask is missing generic type parameters—let’s fix that, and add an onPostExecute method to handle the parsing (or you can parse directly in doInBackground if you don’t need to update the UI right away):
private class Connection extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... arg0) { try { DefaultHttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet("http://server5.onlinegpstracker.com/xml_files/2501_group_summary.xml"); HttpResponse response = client.execute(request); HttpEntity httpEntity = response.getEntity(); return EntityUtils.toString(httpEntity); } catch (ClientProtocolException e) { Log.d("HTTPCLIENT", e.getLocalizedMessage()); } catch (IOException e) { Log.d("HTTPCLIENT", e.getLocalizedMessage()); } return null; } @Override protected void onPostExecute(String xmlContent) { super.onPostExecute(xmlContent); if (xmlContent != null) { try { String geopoint = extractGeopointFromXml(xmlContent); // Now you can use this geopoint value—display it in a TextView, etc. Log.d("GEOPOINT", "Found value: " + geopoint); } catch (XmlPullParserException | IOException e) { Log.e("XML_PARSER", "Error parsing XML", e); } } } }
Method 2: Using DOM Parser (Alternative)
If you prefer a more document-oriented approach, you can use the DOM parser. Here’s a quick helper method for that:
private String extractGeopointWithDom(String xmlContent) throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(xmlContent))); // Get all ReportBody nodes NodeList reportBodyNodes = doc.getElementsByTagName("ReportBody"); // Loop through nodes to find index=1 for (int i = 0; i < reportBodyNodes.getLength(); i++) { Element reportBody = (Element) reportBodyNodes.item(i); String indexAttr = reportBody.getAttribute("index"); if ("1".equals(indexAttr)) { // Get the geopoint child node's text Element geopointElement = (Element) reportBody.getElementsByTagName("geopoint").item(0); return geopointElement.getTextContent(); } } return null; }
You can call this method in onPostExecute just like the XmlPullParser version.
Quick Notes:
- Permissions: Make sure you have the
<uses-permission android:name="android.permission.INTERNET" />permission in yourAndroidManifest.xml(you probably already have this since you’re fetching XML). - Deprecated HttpClient: Note that
DefaultHttpClientis deprecated in newer Android versions. For better compatibility, consider switching toHttpURLConnectionor a library like OkHttp—though the parsing logic remains identical regardless of how you fetch the XML.
内容的提问来源于stack exchange,提问作者arjun babu

