解析网络XML
第一步:需在项目的根目录下面配置网络权限
<uses-permission android:name="android.permission.INTERNET"/>
第二部:写一个简单的布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"
android:layout_width="match_parent" android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.asus.android_29_parsexml.MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="解析XML"
android:onClick="parseXML"
/>
</LinearLayout>
package com.asus.android_29_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) {
//01.获取网络xml
new MyTask().execute();
//02.解析XML
//03.展示
}
class MyTask extends AsyncTask{
@Override
protected Object doInBackground(Object[] params) {
//原生态底层:
try {
URL url=new URL("http://192.168.43.231:8080/persons.xml");
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
//设置请求方式‘
connection.setRequestMethod("GET");
//设置请求连接超时的时间(优化)
connection.setConnectTimeout(5000);
//获取结果码
int code=connection.getResponseCode();
if(code==200){
//获取服务器返回过来的结果
InputStream is=connection.getInputStream();
//打印(读)--》测试
// BufferedReader br=new BufferedReader(new InputStreamReader(is));
// String str=null;
// while((str=br.readLine())!=null){
// Log.i("test",str);
// }
//解析
// //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>下面的所有的子标签<person>
// NodeList nodeList=root.getElementsByTagName("person");
// for (int i = 0; i <nodeList.getLength() ; i++) {
// //获取单个
// //Node
// //Element
// Element personElement= (Element) nodeList.item(i);
// //获取<person>属性id的值
// String id=personElement.getAttribute("id");
// Log.i("test",id);
//
// //获取<person>下面的子标签<name><age><image>的值
// Element nameElement= (Element) personElement.getElementsByTagName("name").item(0);
// String name=nameElement.getTextContent();
// Element ageElement= (Element) personElement.getElementsByTagName("age").item(0);
// String age=ageElement.getTextContent();
//
// Log.i("test",name+" "+age);
// }
//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)){
// //获取<name>的值
// String name=new String(ch,start,length);
// Log.i("test", " "+name);
// }else if("age".equals(cuurentTag)){
// //获取<name>的值
// String age=new String(ch,start,length);
// Log.i("test", " "+age);
// }
// }
// });
//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)){
String name=xmlPullParser.nextText();
Log.i("test",name);
}else if("age".equals(starttagName)){
String age=xmlPullParser.nextText();
Log.i("test",age);
}
break;
case XmlPullParser.END_TAG:
break;
}
//细节:
type=xmlPullParser.next();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
}
}
}
注: onPostExecute用于展示数据;