package com.tarena.parse.xml.util;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xmlpull.v1.XmlPullParser;
import android.util.Xml;
/*解析xml文件*/
public class ParseXMLUtil {
// 得到xml文件转换成输入流然后用pull解析器解析;
public List<Album> getXMLAlbum(String url) {
HttpUtil mHttpUtil = new HttpUtil();
String albumXML = mHttpUtil.rentunHttpGet(url);
InputStream albumXMLInputStream = new ByteArrayInputStream(
albumXML.getBytes());
return getPullAlbumXML(albumXMLInputStream);
}
// 以下是三种解析xml的方法
public static List<Album> getSaxAlbumXML(InputStream inStream) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser saxParser = spf.newSAXParser(); // 创建解析器
//指定如何解析XML
saxAlbumXMLHandler handler = new saxAlbumXMLHandler();
//指定解析数据(inStream)和解析者(handler)
saxParser.parse(inStream, handler);
inStream.close();
return handler.getAlbums();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public List<Album> getDomAlbumXML(InputStream inStream) {
List<Album> Albums = new ArrayList<Album>();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(inStream);
Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("album");// 查找所有Album节点
for (int i = 0; i < items.getLength(); i++) {
Album Album = new Album();
// 得到第一个Album节点
Element AlbumNode = (Element) items.item(i);
// 获取Album节点的id属性值
Album.id = AlbumNode.getAttribute("id");
// 获取Album节点下的所有子节点(标签之间的空白节点和name/age元素)
NodeList childsNodes = AlbumNode.getChildNodes();
for (int j = 0; j < childsNodes.getLength(); j++) {
Node node = (Node) childsNodes.item(j); // 判断是否为元素类型
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element childNode = (Element) node;
// 判断是否name元素
if ("artist_name".equals(childNode.getNodeName())) {
// 获取name元素下Text节点,然后从Text节点获取数据
Album.artist_name = childNode.getFirstChild()
.getNodeValue();
} else if ("image".equals(childNode.getNodeName())) {
Album.image = childNode.getFirstChild()
.getNodeValue();
} else if ("name".equals(childNode.getNodeName())) {
Album.name = childNode.getFirstChild()
.getNodeValue();
} else if ("rating".equals(childNode.getNodeName())) {
Album.rating = childNode.getFirstChild()
.getNodeValue();
} else if ("url".equals(childNode.getNodeName())) {
Album.url = childNode.getFirstChild()
.getNodeValue();
}
}
}
Albums.add(Album);
}
inStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return Albums;
}
public static List<Album> getPullAlbumXML(InputStream inStream) {
//強烈建议使用pull
XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(inStream, "UTF-8");
int eventType = parser.getEventType();
Album currentAlbum = null;
List<Album> Albums = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:// 文档开始事件,可以进行数据初始化处理
Albums = new ArrayList<Album>();
break;
case XmlPullParser.START_TAG:// 开始元素事件
String name = parser.getName();
if (name.equalsIgnoreCase("album")) {
currentAlbum = new Album();
currentAlbum.id =parser.getAttributeValue(null, "id");
} else if (currentAlbum != null) {
if (name.equalsIgnoreCase("artist_name")) {
// 如果后面是Text元素,即返回它的值
currentAlbum.artist_name=parser.nextText();
} else if (name.equalsIgnoreCase("image")) {
currentAlbum.image = parser.nextText();
} else if (name.equalsIgnoreCase("name")) {
currentAlbum.name = parser.nextText();
} else if (name.equalsIgnoreCase("rating")) {
currentAlbum.rating = parser.nextText();
} else if (name.equalsIgnoreCase("url")) {
currentAlbum.url = parser.nextText();
}
}
break;
case XmlPullParser.END_TAG:// 结束元素事件
if (parser.getName().equalsIgnoreCase("album")
&& currentAlbum != null) {
Albums.add(currentAlbum);
currentAlbum = null;
}
break;
}
eventType = parser.next();
}
inStream.close();
return Albums;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Defaulthandler 类
package com.tarena.parse.xml.util;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class saxAlbumXMLHandler extends DefaultHandler {
private List<Album> albums = null;
private Album currentAlbum;
private String tagName = null;// 当前解析的元素标签
public List<Album> getAlbums() {
return albums;
}
/*
* 接收文档的开始的通知。
*/
@Override
public void startDocument() throws SAXException {
albums = new ArrayList<Album>();
}
/*
* 接收字符数据的通知。
*/
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (tagName != null) {
String data = new String(ch, start, length);
if (tagName.equals("artist_name")) {
this.currentAlbum.artist_name = data;
} else if (tagName.equals("image")) {
this.currentAlbum.image = data;
} else if (tagName.equals("name")) {
this.currentAlbum.name = data;
} else if (tagName.equals("rating")) {
this.currentAlbum.rating = data;
} else if (tagName.equals("url")) {
this.currentAlbum.url = data;
}
}
}
/*
* 接收元素开始的通知。 参数意义如下: namespaceURI:元素的命名空间 localName :元素的本地名称(不带前缀) qName
* :元素的限定名(带前缀) atts :元素的属性集合
*/
@Override
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
if (localName.equals("album")) {
currentAlbum = new Album();
currentAlbum.id = atts.getValue("id");
}
this.tagName = localName;
}
/*
* 接收文档的结尾的通知。 参数意义如下: uri :元素的命名空间 localName :元素的本地名称(不带前缀) name
* :元素的限定名(带前缀)
*/
@Override
public void endElement(String uri, String localName, String name)
throws SAXException {
if (localName.equals("album")) {
albums.add(currentAlbum);
currentAlbum = null;
}
this.tagName = null;
}
}
Album类
package com.tarena.parse.xml.util;
public class Album {
public String artist_name;
public String id;
public String image;
public String name;
public String rating;
public String url;
}
HttpUtil
package com.tarena.parse.xml.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.net.Uri;
public class HttpUtil {
public String rentunHttpGet(String url) {
String data = null;
try {
//记录网址
URI encodedUri = null;
encodedUri = new URI(url);
//生成Http的Get方式请求
HttpGet httpGet = null;
httpGet = new HttpGet(encodedUri);
//创建一个Http客户端
HttpClient httpClient = new DefaultHttpClient();
//通过Http客户端执行httpGet请求
HttpResponse httpResponse = httpClient.execute(httpGet);
// 将httpResponse获得的返回数据实体给httpEntity
Header[] strHead = httpResponse.getHeaders("Server");
HttpEntity httpEntity = httpResponse.getEntity();
//将返回的数据转换为字符串
if(httpEntity != null){
InputStream inputStream = httpEntity.getContent();
data = convertStreamToString(inputStream);
}
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//返回转换后的字符串数据
return data;
}
private static String convertStreamToString(InputStream is) {
//读取的BufferedReader 是http输入流为数据源
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
//拼装字符串的StringBuilder
StringBuilder sb = new StringBuilder();
//循环读取所有的返回数据,并转换为字符串
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//收尾,关闭http数据流
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//返回拼装好的字符串
return sb.toString();
}
}
json 解析
package com.tarena.parse.xml.util;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import android.telephony.gsm.GsmCellLocation;
public class ParseJsonUtil {
public List<Album> getJsonAlbum(String url) {
HttpUtil mHttpUtil = new HttpUtil();
String albumJson = mHttpUtil.rentunHttpGet(url);
try {
JSONArray jsonArrayAlbums = new JSONArray(albumJson);
return getAlbumList(jsonArrayAlbums);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private List<Album> getAlbumList(JSONArray jsonArrayAlbums)
throws JSONException {
Album album;
List<Album> albumList = new ArrayList<Album>();
//转化为是实体类
for (int i = 0; i < jsonArrayAlbums.length(); i++) {
album = new Album();
album.id = jsonArrayAlbums.getJSONObject(i).getString("id");
album.artist_name = jsonArrayAlbums.getJSONObject(i).getString("artist_name");
album.image = jsonArrayAlbums.getJSONObject(i).getString("image");
album.name = jsonArrayAlbums.getJSONObject(i).getString("name");
album.rating = jsonArrayAlbums.getJSONObject(i).getString("rating");
album.url = jsonArrayAlbums.getJSONObject(i).getString("url");
albumList.add(album);
}
return albumList;
}
}