Android 中创建与解析XML的方法

大家好今天我今天给大家讲解一下android中xml的创建以及一些解析xml的常用方法。首先是创建,我们用XmlSerializer这个类来创建一个xml文件,其次是解析xml文件,常用的有dom, sax, XmlPullParser等方法,由于sax代码有点复杂,本节只讲解一下dom与XmlPullParser解析,sax我将会在下一节单独讲解,至于几种解析xml的优缺点我就不再讲述了。

为了方便理解,我做了一个简单的Demo。首先首界面有三个按钮,点击第一个按钮会在sdcard目录下创建一个books.xml文件,另外两个按钮分别是调用dom与XmlPullParser方法解析xml文件,并将结果显示在一个TextView里。大家可以按照我的步骤一步步来:
第一步:新建一个Android工程,命名为XmlDemo.
第二步:修改main.xml布局文件,代码如下:
view source
print ?
01 <?xml version="1.0" encoding="utf-8"?> 
02 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
03 android:orientation="vertical" 
04 android:layout_width="fill_parent" 
05 android:layout_height="fill_parent" 
06
07 <Button 
08 android:id="@+id/btn1" 
09 android:layout_width="fill_parent" 
10 android:layout_height="wrap_content" 
11 android:text="创建XML文件" 
12 /> 
13 <Button 
14 android:id="@+id/btn2" 
15 android:layout_width="fill_parent" 
16 android:layout_height="wrap_content" 
17 android:text="DOM解析XML" 
18 /> 
19 <Button 
20 android:id="@+id/btn3" 
21 android:layout_width="fill_parent" 
22 android:layout_height="wrap_content" 
23 android:text="XmlPullParse解析XML" 
24 /> 
25 <TextView 
26 android:id="@+id/result" 
27 android:layout_width="fill_parent" 
28 android:layout_height="wrap_content" 
29 /> 
30 </LinearLayout>
第三步:修改主核心程序XmlDemo.java,代码如下:
view source
print ?
001 package com.tutor.xml; 
002 import java.io.File; 
003 import java.io.FileNotFoundException; 
004 import java.io.FileOutputStream; 
005 import java.io.IOException; 
006 import javax.xml.parsers.DocumentBuilder; 
007 import javax.xml.parsers.DocumentBuilderFactory; 
008 import javax.xml.parsers.ParserConfigurationException; 
009 import org.w3c.dom.Document; 
010 import org.w3c.dom.Element; 
011 import org.w3c.dom.NodeList; 
012 import org.xml.sax.SAXException; 
013 import org.xmlpull.v1.XmlPullParser; 
014 import org.xmlpull.v1.XmlPullParserException; 
015 import org.xmlpull.v1.XmlPullParserFactory; 
016 import org.xmlpull.v1.XmlSerializer; 
017 import android.app.Activity; 
018 import android.os.Bundle; 
019 import android.util.Log; 
020 import android.util.Xml; 
021 import android.view.View; 
022 import android.view.View.OnClickListener; 
023 import android.widget.Button; 
024 import android.widget.TextView; 
025 import android.widget.Toast; 
026 public class XmlDemo extends Activity implements OnClickListener { 
027   
028 private static final String BOOKS_PATH = "/sdcard/books.xml"
029 private Button mButton1,mButton2,mButton3; 
030 private TextView mTextView; 
031 @Override 
032 public void onCreate(Bundle savedInstanceState) { 
033 super.onCreate(savedInstanceState); 
034 setContentView(R.layout.main); 
035 setupViews(); 
036
037 //初始化工作 
038 private void setupViews(){ 
039 mTextView = (TextView)findViewById(R.id.result); 
040 mButton1 = (Button)findViewById(R.id.btn1); 
041 mButton2 = (Button)findViewById(R.id.btn2); 
042 mButton3 = (Button)findViewById(R.id.btn3); 
043 mButton1.setOnClickListener(this); 
044 mButton2.setOnClickListener(this); 
045 mButton3.setOnClickListener(this); 
046
047 //创建xml文件 
048 private void createXmlFile(){ 
049 File linceseFile = new File(BOOKS_PATH); 
050 try
051 linceseFile.createNewFile(); 
052 }catch (IOException e) { 
053 Log.e("IOException", "exception in createNewFile() method"); 
054
055 FileOutputStream fileos = null
056 try
057 fileos = new FileOutputStream(linceseFile); 
058 }catch (FileNotFoundException e) { 
059 Log.e("FileNotFoundException", "can't create FileOutputStream"); 
060
061 XmlSerializer serializer = Xml.newSerializer(); 
062 try
063 serializer.setOutput(fileos,"UTF-8"); 
064 serializer.startDocument(null, true); 
065 serializer.startTag(null, "books"); 
066 for(int i = 0; i < 3; i ++){ 
067 serializer.startTag(null, "book"); 
068 serializer.startTag(null, "bookname"); 
069 serializer.text("Android教程" + i); 
070 serializer.endTag(null, "bookname"); 
071 serializer.startTag(null, "bookauthor"); 
072 serializer.text("Frankie" + i); 
073 serializer.endTag(null, "bookauthor"); 
074 serializer.endTag(null, "book"); 
075
076   
077 serializer.endTag(null, "books"); 
078 serializer.endDocument(); 
079 serializer.flush(); 
080 fileos.close(); 
081 } catch (Exception e) { 
082 Log.e("Exception","error occurred while creating xml file"); 
083
084 Toast.makeText(getApplicationContext(), "创建xml文件成功!", Toast.LENGTH_SHORT).show(); 
085
086 //dom解析xml文件 
087 private void domParseXML(){ 
088 File file = new File(BOOKS_PATH); 
089 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
090 DocumentBuilder db = null
091 try
092 db = dbf.newDocumentBuilder(); 
093 } catch (ParserConfigurationException e) { 
094 e.printStackTrace(); 
095
096 Document doc = null
097 try
098 doc = db.parse(file); 
099 } catch (SAXException e) { 
100 e.printStackTrace(); 
101 } catch (IOException e) { 
102 e.printStackTrace(); 
103
104 Element root = doc.getDocumentElement(); 
105 NodeList books = root.getElementsByTagName("book"); 
106 String res = "本结果是通过dom解析:" + "/n"
107 for(int i = 0; i < books.getLength();i++){ 
108 Element book = (Element)books.item(i); 
109 Element bookname = (Element)book.getElementsByTagName("bookname").item(0); 
110 Element bookauthor = (Element)book.getElementsByTagName("bookauthor").item(0); 
111 res += "书名: " + bookname.getFirstChild().getNodeValue() + " "
112 "作者: " + bookauthor.getFirstChild().getNodeValue() + "/n"
113
114   
115 mTextView.setText(res); 
116
117   
118 //xmlPullParser解析xml文件 
119 private void xmlPullParseXML(){ 
120 String res = "本结果是通过XmlPullParse解析:" + "/n"
121 try
122 XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 
123 XmlPullParser xmlPullParser = factory.newPullParser(); 
124   
125 xmlPullParser.setInput(Thread.currentThread().getContextClassLoader() 
126 .getResourceAsStream(BOOKS_PATH), "UTF-8"); 
127   
128 int eventType = xmlPullParser.getEventType(); 
129   
130 try
131 while (eventType != XmlPullParser.END_DOCUMENT) { 
132 String nodeName = xmlPullParser.getName(); 
133 switch (eventType) { 
134 case XmlPullParser.START_TAG: 
135 if("bookname".equals(nodeName)){ 
136 res += "书名: " + xmlPullParser.nextText() + " "
137 }else if("bookauthor".equals(nodeName)){ 
138 res += "作者: " + xmlPullParser.nextText() + "/n"
139
140 break
141 default
142 break
143
144 eventType = xmlPullParser.next(); 
145
146 } catch (IOException e) { 
147 e.printStackTrace(); 
148
149 } catch (XmlPullParserException e) { 
150 e.printStackTrace(); 
151
152   
153 mTextView.setText(res); 
154
155 //按钮事件响应 
156 public void onClick(View v) { 
157 if(v == mButton1){ 
158 createXmlFile(); 
159 }else if(v == mButton2){ 
160 domParseXML(); 
161 }else if(v == mButton3){ 
162 xmlPullParseXML(); 
163
164
165 }
第四步:由于我们在Sd卡上新建了文件,需要增加权限,如下代码(第16行):
view source
print ?
01 <?xml version="1.0" encoding="utf-8"?> 
02 <manifest xmlns:android="http://schemas.android.com/apk/res/android" 
03 package="com.tutor.xml" 
04 android:versionCode="1" 
05 android:versionName="1.0"
06 <application android:icon="@drawable/icon" android:label="@string/app_name"
07 <activity android:name=".XmlDemo" 
08 android:label="@string/app_name"
09 <intent-filter
10 <action android:name="android.intent.action.MAIN" /> 
11 <category android:name="android.intent.category.LAUNCHER" /> 
12 </intent-filter
13 </activity
14 </application
15 <uses-sdk android:minSdkVersion="7" /> 
16 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
17 </manifest>
第五步:运行上述工程,查看效果:
启动首界面:


点击创建XML文件按钮,生成books.xml文件
Android 中创建与解析XML的方法_第1张图片
books.xml内容如下:
view source
print ?
01 <?xml version='1.0' encoding='UTF-8' standalone='yes' ?> 
02 <books
03 <book
04 <bookname>Android教程0</bookname
05 <bookauthor>Frankie0</bookauthor
06 </book
07 <book
08 <bookname>Android教程1</bookname
09 <bookauthor>Frankie1</bookauthor
10 </book
11 <book
12 <bookname>Android教程2</bookname
13 <bookauthor>Frankie2</bookauthor
14 </book
15 </books>
点击DOM解析XML按钮:


点击XmlPullParse解析XML按钮:

你可能感兴趣的:(xml)