Android开发中dom和XmlPullParser解析xml文件的方法
做了一个简单的Demo。首先首界面有三个按钮,点击第一个按钮会在sdcard目录下创建一个books.xml文件,另外两个按钮分别是调用dom与XmlPullParser方法解析xml文件,并将结果分别显示在一个TextView里。大家可以按照我的步骤一步步来:
第二步:修改布局文件,代码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent" >
<Button
android:id="@+id/bn1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="创建XML文件"
/>
<Button
android:id="@+id/bn2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="DOM解析XML"
/>
<Button
android:id="@+id/bn3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="XmlPullParse解析XML"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/result"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/result1"
/>
</LinearLayout>
第三步:修改主核心程序MainActivity.java,比较长代码如下:
package com.example.xml;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;
import android.os.Bundle;
import android.app.Activity;
import android.sax.Element;
import android.util.Log;
import android.util.Xml;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String BOOKS_PATH="/sdcard/books.xml";
private Button bn1,bn2,bn3;
private TextView textview,textview1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupViews();
bn1.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
createxml();
}
});
bn2.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
domParseXML();
}
});
bn3.setOnClickListener(new OnClickListener()
{public void onClick(View v) {
// TODO Auto-generated method stub
xmlPullParseXML();
}
});
}
//创建XML文件
private void createxml()
{
File file=new File(BOOKS_PATH);
try
{
file.createNewFile();
}
catch(IOException e)
{
e.printStackTrace();
Log.v("IOException", "exception in createnewfile() method");
}
FileOutputStream fis=null;
try
{
fis=new FileOutputStream(file);
}
catch(FileNotFoundException e)
{
e.printStackTrace();
Log.v("FileNotFoundException", "can't create file fileoutputStream");
}
XmlSerializer serializer=Xml.newSerializer();
try
{
serializer.setOutput(fis,"UTF-8");
serializer.startDocument(null, true);
serializer.startTag(null, "books");
for(int i=0;i<3;i++)
{
serializer.startTag(null, "book");
serializer.startTag(null, "bookname");
serializer.text("Android教程"+i);
serializer.endTag(null, "bookname");
serializer.startTag(null, "bookauthor");
serializer.text("xiaoshu"+i);
serializer.endTag(null, "bookauthor");
serializer.endTag(null, "book");
}
serializer.endTag(null, "books");
serializer.endDocument();
serializer.flush();
fis.close();
}
catch(IOException e)
{
e.printStackTrace();
Log.v("IOException", "can't create xml file");
}
Toast.makeText(MainActivity.this, "创建xml文件成功", Toast.LENGTH_SHORT).show();
}
//dom解析xml文件
private void domParseXML()
{
File file=new File(BOOKS_PATH);
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=null;
try
{
db=dbf.newDocumentBuilder();
}
catch(ParserConfigurationException e)
{
e.printStackTrace();
}
Document doc=null;
try
{
doc=db.parse(file);
}
catch(SAXException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
org.w3c.dom.Element root=doc.getDocumentElement();
NodeList books= ((org.w3c.dom.Element) root).getElementsByTagName("book");
String res="本结果是通过dom解析的:"+"\n";
for(int i=0;i<books.getLength();i++)
{
Node book=books.item(i);
Node bookname=((org.w3c.dom.Element) book).getElementsByTagName("bookname").item(0);
Node bookauthor =((org.w3c.dom.Element) book).getElementsByTagName("bookauthor").item(0);
res+="书名:"+((Node) bookname).getFirstChild().getNodeValue()+""+
"作者:"+((Node) bookauthor).getFirstChild().getNodeValue()+"\n";
}
textview.setText(res);
Toast.makeText(MainActivity.this, "解析成功", Toast.LENGTH_SHORT).show();
}
//xmlPullParse解析xml文件
private void xmlPullParseXML()
{
String res="本结果通过XmlPullParse解析:"+"\n";
try
{
XmlPullParserFactory factory=XmlPullParserFactory.newInstance();
XmlPullParser xmlpullparser=factory.newPullParser();
this.getClass().getClassLoader();
xmlpullparser.setInput(ClassLoader.getSystemResourceAsStream(BOOKS_PATH),"UTF-8");
int eventType=xmlpullparser.getEventType();
try
{
while(eventType!=XmlPullParser.END_DOCUMENT)
{
String nodename=xmlpullparser.getName();
switch(eventType)
{
case XmlPullParser.START_TAG:
if("bookname".equals(nodename))
{
res+="书名:"+xmlpullparser.nextText()+"";
}
else if("bookauthor".equals(nodename))
{
res+="作者:"+xmlpullparser.nextText()+"\n";
}
break;
default:
break;
}
eventType=xmlpullparser.next();
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
catch(XmlPullParserException e)
{
e.printStackTrace();
}
textview1.setText(res);
Toast.makeText(MainActivity.this, "XmlPullParser解析成功", Toast.LENGTH_SHORT).show();
}
private void setupViews()
{
bn1=(Button)findViewById(R.id.bn1);
bn2=(Button)findViewById(R.id.bn2);
bn3=(Button)findViewById(R.id.bn3);
textview=(TextView)findViewById(R.id.result);
textview1=(TextView)findViewById(R.id.result1);
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
第四步:由于我们在Sd卡上新建了文件,需要增加权限,如下代码(第24行):
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.xml"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>
第五步:运行上述工程,查看效果:
OK,三个按钮分别是创建xml文件和两种不同解析的方法,创建的xml文件在sd卡里面,程序中已经有路径了