Android解析XML有三种…..
1.使用DOM解析。
2.使用SAX解析。
3.使用Pull解析。
4.解析前的效果。
5.解析后的效果。
6.下面直接上代码,三种解析方法都在其中
`package com.thm.android_parsexml;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class MainActivity extends AppCompatActivity {
private String cuurentTag = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void parseXML(View view){
new MyTask().execute();
}
class MyTask extends AsyncTask{
@Override
protected Object doInBackground(Object[] params) {
{
//01.获取网络XML数据
//原生态底层: URLConnection
try {
URL url = new URL("http://193.168.2.223:8080/persons.xml");
//打开连接
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//设置请求方式
httpURLConnection.setRequestMethod("GET");
//设置请求连接超时时间(优化)
httpURLConnection.setConnectTimeout(5000);
//获取结果码(状态) 成功:200 未修改:304
int code = httpURLConnection.getResponseCode();
if(code==200){
//获取服务器返回过来的结果
InputStream is = httpURLConnection.getInputStream();
// //打印(读)
// BufferedReader br = new BufferedReader(new InputStreamReader(is));
// String str = null;
// while((str=br.readLine())!=null){
// Log.i(“test”,str);
// }
//解析XML
//01.DOM解析
// DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
// DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
// Document document = documentBuilder.parse(is);
// //获取根标签
// Element root = document.getDocumentElement();
// Log.i(“test”,”根标签为:”+root.getNodeName());
// //获取persons下面所有的子标签
// NodeList nodeList = root.getElementsByTagName(“person”);
// for (int i = 0; i < nodeList.getLength(); i++) {
// //获取单个
// Element personElement = (Element) nodeList.item(i);
// //获取属性ID的值
// String id = personElement.getAttribute(“id”);
// Log.i(“test”,id);
// //获取子标签的值
// Element nameElement = (Element) personElement.getElementsByTagName(“name”).item(0);
// String name = nameElement.getTextContent();
//
// Element ageElement = (Element) personElement.getElementsByTagName(“age”).item(0);
// String age = ageElement.getTextContent();
//
// Element sexElement = (Element) personElement.getElementsByTagName(“sex”).item(0);
// String sex = sexElement.getTextContent();
//
// Log.i(“test”,name+” “+age+” “+sex);
// }
//02.SAX解析(边读边解析,基于事件(方法)驱动的方式)
// SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
// SAXParser saxParser = saxParserFactory.newSAXParser();
// saxParser.parse(is,new DefaultHandler(){
// @Override
// public void startDocument() throws SAXException {
// super.startDocument();
// }
//
// @Override
// public void endDocument() throws SAXException {
// super.endDocument();
//
// }
//
// @Override
// public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
// super.startElement(uri, localName, qName, attributes);
// cuurentTag=localName;
// //获取开始标签的名字
// if(“person”.equals(localName)){
// //获取属性的值
// String id = attributes.getValue(0);
// Log.i(“test”,id);
// }
// }
//
// @Override
// public void endElement(String uri, String localName, String qName) throws SAXException {
// super.endElement(uri, localName, qName);
// cuurentTag=null;
// }
//
// @Override
// public void characters(char[] ch, int start, int length) throws SAXException {
// super.characters(ch, start, length);
// if(“name”.equals(cuurentTag)){
// //获取的值
// String name = new String(ch,start,length);
// Log.i(“test”,” “+name);
// }else if(“age”.equals(cuurentTag)){
// //获取的值
// String age = new String(ch,start,length);
// Log.i(“test”,” “+age);
// }else if(“sex”.equals(cuurentTag)){
// //获取的值
// String sex = new String(ch,start,length);
// Log.i(“test”,” “+sex);
// }
// }
// });
//03.使用Pull解析(类似SAX)
XmlPullParser xmlPullParser = Xml.newPullParser();
xmlPullParser.setInput(is,"UTF-8");
//获取解析标签的类型
int type = xmlPullParser.getEventType();
while(type!=XmlPullParser.END_DOCUMENT){
switch (type){
case XmlPullParser.START_TAG:
//获取开始标签的名字
String startTagName = xmlPullParser.getName();
if("person".equals(startTagName)){
//获取ID的值
String id = xmlPullParser.getAttributeValue(0);
Log.i("test",id);
}else if ("name".equals(startTagName)){
//获取name的值
String name = xmlPullParser.nextText();
Log.i("test",name);
}else if ("sex".equals(startTagName)){
//获取sex的值
String sex = xmlPullParser.nextText();
Log.i("test",sex);
}
break;
case XmlPullParser.END_TAG:
break;
}
//细节:重新赋值,不然会造成死循环
type=xmlPullParser.next();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
// catch (ParserConfigurationException e) {
// e.printStackTrace();
// } catch (SAXException e) {
// e.printStackTrace();
// }
// catch (ParserConfigurationException e) {
// e.printStackTrace();
// } catch (SAXException e) {
// e.printStackTrace();
// }
//03.展示
}
return null;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
}
}
}
7.当然最后不要忘了在Manifests中配置网络权限哟
<!--配置网络权限-->
<uses-permission android:name="android.permission.INTERNET"></uses-permission>