传送门 ☞ 轮子的专栏 ☞ 转载请注明 ☞ http://blog.csdn.net/leverage_1229
4MyXmlParser案例
4.1案例代码陈列
待解析的xml格式数据:source.xml
<?xml version="1.0" encoding="UTF-8"?> <xml> <android id="1"> <version>1.5</version> <name>Cupcake</name> </android> <android id="2"> <version>1.6</version> <name>Donut</name> </android> <android id="3"> <version>2.1</version> <name>Eclair</name> </android> <android id="4"> <version>2.2</version> <name>Froyo</name> </android> <android id="5"> <version>2.3</version> <name>Gingerbread</name> </android> <android id="6"> <version>3.0</version> <name>Honeycomb</name> </android> <android id="7"> <version>4.0</version> <name>Ice Cream Sandwich</name> </android> <android id="8"> <version>4.1</version> <name>Jelly Bean</name> </android> </xml>
listview.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="top" > <Button android:id="@+id/btnSAX" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="SAX解析" /> <Button android:id="@+id/btnPull" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="Pull解析" /> <Button android:id="@+id/btnDom" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="DOM解析" /> </LinearLayout> <ListView android:id="@+id/listview" android:layout_width="match_parent" android:layout_height="wrap_content" > </ListView> </LinearLayout>
listitem.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:gravity="center" > <ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" android:layout_weight="1" /> <TextView android:id="@+id/textid" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" /> <TextView android:id="@+id/textversion" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" /> <TextView android:id="@+id/textname" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" /> </LinearLayout>
IMyParser.java
package com.leverage.myxmlparser; import java.io.InputStream; import java.util.HashMap; import java.util.List; public interface IMyParser { public static final String ELEMENT_ANDROID = "android"; public static final String ELEMENT_ID = "id"; public static final String ELEMENT_VERSION = "version"; public static final String ELEMENT_NAME = "name"; public void parse(InputStream in) throws Exception; public List<HashMap<String, String>> getResult(); }
MySAXParser.java
package com.leverage.myxmlparser; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; public class MySAXParser implements IMyParser { private List<HashMap<String, String>> datas; // 存储所有的解析对象 @Override public void parse(InputStream in) throws Exception { SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); SAXParser saxParser = saxParserFactory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setContentHandler(new MySAXHandler()); xmlReader.parse(new InputSource(in)); } @Override public List<HashMap<String, String>> getResult() { return datas; } private class MySAXHandler extends DefaultHandler { private String currentElement; // 当前解析的元素 private HashMap<String, String> data; // 存储单个的解析对象 @Override public void startDocument() throws SAXException { super.startDocument(); datas = new ArrayList<HashMap<String, String>>(); } // uri 命名空间URI // localName 不带命名空间标签的元素名 // qName 带命名空间的元素名 // attributes 元素属性 @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { super.startElement(uri, localName, qName, attributes); currentElement = localName; if (ELEMENT_ANDROID.equals(currentElement)) { data = new HashMap<String, String>(); } if(attributes != null && data != null) { for (int i = 0; i < attributes.getLength(); i++) { data.put(attributes.getLocalName(i), attributes.getValue(i)); } } } @Override public void characters(char[] ch, int start, int length) throws SAXException { super.characters(ch, start, length); String tmp = new String(ch, start, length); boolean flag = !tmp.trim().equals("") && !tmp.trim().equals("\n"); if (ELEMENT_VERSION.equals(currentElement) && flag) { data.put(ELEMENT_VERSION, tmp); } else if (ELEMENT_NAME.equals(currentElement) && flag) { data.put(ELEMENT_NAME, tmp); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { super.endElement(uri, localName, qName); if (ELEMENT_ANDROID.equals(localName)) { datas.add(data); } } } }
MyPullParser.java
package com.leverage.myxmlparser; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.xmlpull.v1.XmlPullParser; import android.util.Xml; public class MyPullParser implements IMyParser { private HashMap<String, String> data; // 存储单个的解析对象 private List<HashMap<String, String>> datas; // 存储所有的解析对象 @Override public void parse(InputStream in) throws Exception { XmlPullParser xmlPullParser = Xml.newPullParser(); xmlPullParser.setInput(in, "UTF-8"); int eventType = xmlPullParser.getEventType(); while(eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_DOCUMENT: datas = new ArrayList<HashMap<String,String>>(); case XmlPullParser.START_TAG: String tag = xmlPullParser.getName(); if(tag != null && tag.equals(ELEMENT_ANDROID) ) { data = new HashMap<String, String>(); data.put(ELEMENT_ID, xmlPullParser.getAttributeValue(null, ELEMENT_ID)); } else if (data != null) { if(tag.equals(ELEMENT_VERSION)) { data.put(ELEMENT_VERSION, xmlPullParser.nextText()); } else if (tag.equals(ELEMENT_NAME)) { data.put(ELEMENT_NAME, xmlPullParser.nextText()); } } break; case XmlPullParser.END_TAG: if(xmlPullParser.getName().equals(ELEMENT_ANDROID) && data != null) { datas.add(data); data = null; } break; default: break; } eventType = xmlPullParser.next(); } } @Override public List<HashMap<String, String>> getResult() { return datas; } }
MyDOMParser.java
package com.leverage.myxmlparser; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; public class MyDOMParser implements IMyParser { private HashMap<String, String> data; // 存储单个的解析对象 private List<HashMap<String, String>> datas = new ArrayList<HashMap<String,String>>(); // 存储所有的解析对象 @Override public void parse(InputStream in) throws Exception { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(in); Element root = document.getDocumentElement(); NodeList nodes = root.getElementsByTagName(ELEMENT_ANDROID); for (int i = 0; i < nodes.getLength(); i++) { data = new HashMap<String, String>(); Element dataElement = (Element) nodes.item(i); data.put(ELEMENT_ID, dataElement.getAttribute(ELEMENT_ID)); Element verElement = (Element) dataElement.getElementsByTagName(ELEMENT_VERSION).item(0); data.put(ELEMENT_VERSION, verElement.getFirstChild().getNodeValue()); Element nameElement = (Element) dataElement.getElementsByTagName(ELEMENT_NAME).item(0); data.put(ELEMENT_NAME, nameElement.getFirstChild().getNodeValue()); datas.add(data); } } @Override public List<HashMap<String, String>> getResult() { return datas; } }
XmlParserActivity.java
package com.leverage.myxmlparser; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; public class TestXmlParseActivity extends Activity { public static final String TAG = TestXmlParseActivity.class.getSimpleName(); private ListView mListView; private Button mSaxBtn; private Button mPullBtn; private Button mDomBtn; // private IMyParser myParser; private List<HashMap<String, String>> datas = new ArrayList<HashMap<String,String>>(); private MyOnClickListener myOnClickListener = new MyOnClickListener(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listview); mListView = (ListView) findViewById(R.id.listview); mSaxBtn = (Button) findViewById(R.id.btnSAX); mPullBtn = (Button) findViewById(R.id.btnPull); mDomBtn = (Button) findViewById(R.id.btnDom); // InputStream in = null; // try { // in = getAssets().open("source.xml"); // IMyParser myParser = new MySAXParser(); // IMyParser myParser = new MyPullParser(); // IMyParser myParser = new MyDOMParser(); // myParser.parse(in); // datas = myParser.getResult(); // System.out.println("datas = " + datas.toString()); // } catch (Exception e) { // Log.e(TAG, e.getMessage()); // } finally { // if(in != null) { // try { // in.close(); // } catch (IOException e) { // Log.e(TAG, e.getMessage()); // } // } // } mSaxBtn.setOnClickListener(myOnClickListener); mPullBtn.setOnClickListener(myOnClickListener); mDomBtn.setOnClickListener(myOnClickListener); // InputStream in = null; // try { // in = getAssets().open("source.xml"); // IMyParser myParser = new MySAXParser(); // IMyParser myParser = new MyPullParser(); // myParser = new MyDOMParser(); // myParser.parse(in); // datas = myParser.getResult(); // System.out.println("datas = " + datas.toString()); // } catch (Exception e) { // Log.e(TAG, e.getMessage()); // } finally { // if(in != null) { // try { // in.close(); // } catch (IOException e) { // Log.e(TAG, e.getMessage()); // } // } // } // mListView.setAdapter(new MyListAdapter(this, datas)); } private void parseXML(IMyParser parser) { mListView.setAdapter(null); InputStream in = null; try { in = getAssets().open("source.xml"); // IMyParser myParser = new MySAXParser(); // IMyParser myParser = new MyPullParser(); // myParser = new MyDOMParser(); parser.parse(in); datas = parser.getResult(); System.out.println("datas = " + datas.toString()); } catch (Exception e) { Log.e(TAG, e.getMessage()); } finally { if(in != null) { try { in.close(); } catch (IOException e) { Log.e(TAG, e.getMessage()); } } } mListView.setAdapter(new MyListAdapter(this, datas)); } private class MyOnClickListener implements View.OnClickListener { @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnSAX: parseXML(new MySAXParser()); break; case R.id.btnPull: parseXML(new MyPullParser()); break; case R.id.btnDom: parseXML(new MyDOMParser()); break; default: break; } } } private class MyListAdapter extends BaseAdapter { private Context context; private List<HashMap<String, String>> datas; public MyListAdapter(Context context, List<HashMap<String, String>> datas) { this.context = context; this.datas = datas; } @Override public int getCount() { return datas.size(); } @Override public Object getItem(int position) { return datas.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View result = convertView; if(result == null) { result = LayoutInflater.from(context).inflate(R.layout.listitem, null); } TextView idTextView = (TextView) result.findViewById(R.id.textid); TextView versionTextView = (TextView) result.findViewById(R.id.textversion); TextView nameTextView = (TextView) result.findViewById(R.id.textname); idTextView.setText(datas.get(position).get(IMyParser.ELEMENT_ID)); versionTextView.setText(datas.get(position).get(IMyParser.ELEMENT_VERSION)); nameTextView.setText(datas.get(position).get(IMyParser.ELEMENT_NAME)); return result; } } }