北大青鸟学士后

[Android实例] Android之解析XML文件

责任编辑:admin分类:网络营销师案例教学

SAX即是:Simple API for XML。是一种XML解析的替代方法.相比于DOM,SAX是一种速度更快,更有效的方法.它逐行扫描文档,一边扫描一边解析.而且相比于DOM,SAX可以在解析文档的任意时刻停止解析。

下面对对该项目进行分析:

1 .MP3.xml

该文件位于我的web服务器下面的一个工程里(j2ee的web工程)。

这是源代码:

<resources>
<resource>
<id>1001</id>
<mp3name>爱.3gp</mp3name>
<mp3size>4.05M</mp3size>
</resource>
<resource>
<id>1002</id>
<mp3name>你是我的一首歌.mp3</mp3name>
<mp3size>3.08M</mp3size>
</resource>
</resources>

SAX是基于事件驱动的。android的事件机制是基于java中回调函数的。在用Sax解析xml文档的时候,在读取到文档的开始和结束标签时候就会回调一个事件,在读取到其他节点与内容的时候也会回调一个事件。

2.该工程的布局 mian.xml,很简单就是一个按钮和一个listView。采用的是线性布局。

代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
  android:layout_height="wrap_content" android:text="@string/hello" />
<Button android:text="下载" android:id="@+id/button1"
  android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<ListView
android:layout_height="wrap_content"
android:id="@+id/listView1"
android:layout_width="match_parent"></ListView>
</LinearLayout>

3.创建类MyXMLHandler继承默认Handler

MyXMLHandler.java

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class MyXMLHandler extends DefaultHandler {

private Map<String, Object> map;
public List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
String curTag = "";

public List<Map<String, Object>> getListMap() {
  return listMap;
}

public void setListMap(List<Map<String, Object>> listMap) {
  this.listMap = listMap;
}

@Override
public void startElement(String uri, String localName, String qName,
   Attributes attributes) throws SAXException {
  // TODO Auto-generated method stub
  this.curTag = localName;
  if (localName.equals("resource")) {
   map = new HashMap<String, Object>();

  }
  super.startElement(uri, localName, qName, attributes);
}

@Override
public void endElement(String uri, String localName, String qName)
   throws SAXException {
  // TODO Auto-generated method stub

  if (localName.equals("resource")) {

   listMap.add(map);
  }
  curTag="";
  super.endElement(uri, localName, qName);
}

@Override

//内容
public void characters(char[] ch, int start, int length)
   throws SAXException {

  if (curTag.equals("id")) {
   map.put("id", new String(ch));
  }
  if (curTag.equals("mp3name")) {
   map.put("mp3name", new String(ch));
  }
  if (curTag.equals("mp3size")) {
   map.put("mp3size", new String(ch));
  }

  // TODO Auto-generated method stub
  super.characters(ch, start, length);
}

}

4.这是一个Activity是主程序。

DownLoadActivity .java

import java.io.StringReader;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.down.DownFile;

public class DownLoadActivity extends Activity {
private Button but1;
private ListView lv;
MyXMLHandler h;
List<Map<String, Object>> list;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        lv=(ListView) findViewById(R.id.listView1);
        but1=(Button) findViewById(R.id.button1);
        but1.setOnClickListener(new OnClickListener() {
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Thread  t=new Thread(r);
    t.start();
   }
   Handler hand = new Handler() {

    @Override
    public void handleMessage(Message msg) {
     // TODO Auto-generated method stub
     super.handleMessage(msg);
     list=(List<Map<String,Object>>)msg.obj;   
     SimpleAdapter ad=new SimpleAdapter(DownLoadActivity.this, list, android.R.layout.simple_list_item_2, new String[]{"mp3name","mp3size"}, new int[]{android.R.id.text1,android.R.id.text2});
     lv.setAdapter(ad);
    }

   };

         Runnable r=new Runnable(){

    @Override
    public void run() {     
     DownFile d=new DownFile();
     String xmlpath="http://10.0.2.2:8080/xiangce/mp3.xml";
     //d.getMusicContent(xmlpath);
     String xml=d.getXMLContent(xmlpath);
     System.out.println(xml);
     //解析对象工厂-->reader对象 读取对象,处理xml
    try{
      
     SAXParserFactory sf=SAXParserFactory.newInstance();
     SAXParser parse=sf.newSAXParser();
     XMLReader reader=parse.getXMLReader();
     h=new MyXMLHandler();
     reader.setContentHandler(h);
     reader.parse(new InputSource(new StringReader(xml)));
     list=h.getListMap();
     Message mes=new Message();
     mes.obj=list;
     hand.sendMessage(mes);
     System.out.println(list.size());   
     
     }catch(Exception e){
      e.printStackTrace();
     }
    }         
         };   
  });

    }
}

5.下载文件的类,实现了对文件解析方法的封装。

DownFile。java

package com.down;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
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 android.os.Environment;

public class DownFile {
public String getXMLContent(String xmlpath) {
  StringBuilder b=new StringBuilder();
  try {
   //建立URL对象
   URL u =new URL(xmlpath);
   //打开连接
   HttpURLConnection hc=(HttpURLConnection) u.openConnection();
   //获取输入流
   InputStream is=hc.getInputStream();
   //封装输入流为字符流
   BufferedReader br=new BufferedReader(new InputStreamReader(is));
   String str="";
   while((str=br.readLine())!=null){
    b.append(str);
   }
   
  } catch (MalformedURLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  return b.toString();

}

public void getMusicContent(String xmlpath) {
  try{
  URL u =new URL(xmlpath);
  //打开连接
  HttpURLConnection hc=(HttpURLConnection) u.openConnection();
  //获取输入流
  InputStream is=hc.getInputStream();
  File file=Environment.getExternalStorageDirectory();
  FileOutputStream out=new FileOutputStream(file.getAbsolutePath()+""+File.separator+"b.flv");
  byte[] cotent=new byte[1024];
  int len=0;
  while((len=is.read(cotent))!=-1){
   out.write(cotent,0,len);
  }
  out.flush();
  out.close();
  
  
  }catch(Exception e){
   e.printStackTrace();
   
  }
}

}

项目的思路大致是:

处理思路是:

1:创建SAXParserFactory对象

2: 根据SAXParserFactory.newSAXParser()方法返回一个SAXParser解析器
3:根据SAXParser解析器获取事件源对象XMLReader
4:实例化一个DefaultHandler对象

5:连接事件源对象XMLReader到事件处理类DefaultHandler中

6:调用XMLReader的parse方法从输入源中获取到的xml数据

7:通过DefaultHandler返回我们需要的数据集合。

运行该项目之前,我们需要新建一个web工程,然后把需要解析的xml文件放到该项目下,启动web服务器。

项目运行结果是:已经成功解析了!

在线客服乐语