解析XML格式数据的方式——Pull解析、SAX解析
案例http://www.52php.cn/article/p-opmxadok-mn.html 解析XML格式的数据搭建Web服务器
Pull解析方式#public class IndexActivity extends AppCompatActivity implements View.OnClickListener {
..................
private void sendRequestWithHttpClient() {
new Thread(new Runnable() {
@Override
public void run() {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://192.168.0.102" / get_data.xml);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
StatusLine statusLine = httpResponse.getStatusLine();
int code = statusLine.getStatusCode();
if (code == HttpURLConnection.HTTP_OK) {
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity,"utf-8");
InputStream is = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
while (line != null) {
parseXMLWithPull(line);
line = br.readLine();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private void parseXMLWithPull(String xmlData) {
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xmlPullParser = factory.newPullParser();
StringReader stringReader = new StringReader(xmlData);
xmlPullParser.setInput(stringReader);
int eventType = xmlPullParser.getEventType();
String id = "";
String name = "";
String version = "";
while (eventType != XmlPullParser.END_DOCUMENT) {
String nodeName = xmlPullParser.getName();
Switch(eventType) {
case XmlPullParser.START_TAG:
if ("id".equals(nodeName)) {
id = xmlPullParser.nextText();
} else if ("name".equals(nodeName)) {
name = xmlPullParser.nextText();
} else if ("version".equals(nodeName)) {
version = xmlPullParser.nextText();
}
break;
case XmlPullParser.END_TAG:
if ("app".equals(nodeName)){
Log.d("Mainactivity","id is"+id);
Log.d("Mainactivity","id is"+name);
Log.d("Mainactivity","id is"+version);
}
break;
default:
break;
}
eventType=xmlPullParser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
SAX解析方式ContentHandler类MainActivity
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |