package cn.com.zjh.com;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.xmlpull.v1.XmlPullParser;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.util.Xml;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
public static final String TAG="MainActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String path=null;
//获取SD卡路径
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File sdCard=Environment.getExternalStorageDirectory();
path=sdCard.getPath();
}
parseXML(path+"/book.xml");
}
private void parseXML(String path ) {
// TODO Auto-generated method stub
try {
//第一步 获得XML文件的File对象file
File file=new File(path);
//第二步获得file的输入流fis
InputStream fis=new FileInputStream(file);
//第三步创建xmlpullparser对象parser
XmlPullParser parser=Xml.newPullParser();
//第四步 制定输入刘fis 设定编码格式为utf-8
parser.setInput(fis,"utf-8");
//第五步 获得事件类型 开始循环解析
int eventType=parser.getEventType();
boolean stop=false;
//是否解析到xml文件末尾 如果没有继续解析
while(eventType!=XmlPullParser.END_DOCUMENT && !stop){
//第六步 使用switch分析事件条件 解析节点信息
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
Log.d(TAG, "Get Top of XML File");
break;
//开始元素事件
case XmlPullParser.START_TAG:
//第七步 通过getName与nextText方法分别获得节点名称和节点值
String name=parser.getName();
String content=parser.nextText();
if("book".equalsIgnoreCase(name)){
Log.w(TAG, "A Book Parsing Started");
}else{
Log.i(TAG, "Node["+name+"]Parsing Started");
if("bookId".equalsIgnoreCase(name)){
Log.e(TAG, "bookid is ["+content+"]");
}
if("bookName".equalsIgnoreCase(name)){
Log.e(TAG, "bookName is ["+content+"]");
if("DoroLand".equals(content)){
stop=true;
Log.i(TAG, "DoroLand---stop");
}
}
if("vocerPath".equalsIgnoreCase(name)){
Log.e(TAG, "vocerPath is ["+content+"]");
}
if("zipPath".equalsIgnoreCase(name)){
Log.e(TAG, "zipPath is ["+content+"]");
}
if("className".equalsIgnoreCase(name)){
Log.e(TAG, "className is ["+content+"]");
}
}
break;
case XmlPullParser.END_TAG:
name=parser.getName();
if("book".equalsIgnoreCase(name)){
Log.w(TAG, "A book parsing Ended");
break;
}else if("books".equalsIgnoreCase(name)){
Log.w(TAG, "All parsing Ended");
break;
}
Log.i(TAG, "Node is ["+name+"]Parsing Ended");
break;
}
//第八步 查找下一个事件
eventType=parser.next();
}
//第九步 完成解析 关闭流
fis.close();
} catch (Exception e) {
// TODO: handle exception
Log.i(TAG, "parse xml fail"+e.getMessage());
}
}
}