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布局文件,代码如下:
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?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"
>
<Button
android:id= "@+id/btn1"
android:layout_width= "fill_parent"
android:layout_height= "wrap_content"
android:text= "创建XML文件"
/>
<Button
android:id= "@+id/btn2"
android:layout_width= "fill_parent"
android:layout_height= "wrap_content"
android:text= "DOM解析XML"
/>
<Button
android:id= "@+id/btn3"
android:layout_width= "fill_parent"
android:layout_height= "wrap_content"
android:text= "XmlPullParse解析XML"
/>
<TextView
android:id= "@+id/result"
android:layout_width= "fill_parent"
android:layout_height= "wrap_content"
/>
</LinearLayout>


第三步:修改主核心程序XmlDemo.java,代码如下:
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package com.tutor.xml;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
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.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class XmlDemo extends Activity implements OnClickListener {
 
private static final String BOOKS_PATH = "/sdcard/books.xml" ;
private Button mButton1,mButton2,mButton3;
private TextView mTextView;
@Override
public void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.main);
setupViews();
}
//初始化工作
private void setupViews(){
mTextView = (TextView)findViewById(R.id.result);
mButton1 = (Button)findViewById(R.id.btn1);
mButton2 = (Button)findViewById(R.id.btn2);
mButton3 = (Button)findViewById(R.id.btn3);
mButton1.setOnClickListener( this );
mButton2.setOnClickListener( this );
mButton3.setOnClickListener( this );
}
//创建xml文件
private void createXmlFile(){
File linceseFile = new File(BOOKS_PATH);
try {
linceseFile.createNewFile();
} catch (IOException e) {
Log.e( "IOException" , "exception in createNewFile() method" );
}
FileOutputStream fileos = null ;
try {
fileos = new FileOutputStream(linceseFile);
} catch (FileNotFoundException e) {
Log.e( "FileNotFoundException" , "can't create FileOutputStream" );
}
XmlSerializer serializer = Xml.newSerializer();
try {
serializer.setOutput(fileos, "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( "Frankie" + i);
serializer.endTag( null , "bookauthor" );
serializer.endTag( null , "book" );
}
 
serializer.endTag( null , "books" );
serializer.endDocument();
serializer.flush();
fileos.close();
} catch (Exception e) {
Log.e( "Exception" , "error occurred while creating xml file" );
}
Toast.makeText(getApplicationContext(), "创建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();
}
Element root = doc.getDocumentElement();
NodeList books = root.getElementsByTagName( "book" );
String res = "本结果是通过dom解析:" + "/n" ;
for ( int i = 0 ; i < books.getLength();i++){
Element book = (Element)books.item(i);
Element bookname = (Element)book.getElementsByTagName( "bookname" ).item( 0 );
Element bookauthor = (Element)book.getElementsByTagName( "bookauthor" ).item( 0 );
res += "书名: " + bookname.getFirstChild().getNodeValue() + " " +
"作者: " + bookauthor.getFirstChild().getNodeValue() + "/n" ;
}
 
mTextView.setText(res);
}
 
//xmlPullParser解析xml文件
private void xmlPullParseXML(){
String res = "本结果是通过XmlPullParse解析:" + "/n" ;
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xmlPullParser = factory.newPullParser();
 
xmlPullParser.setInput(Thread.currentThread().getContextClassLoader()
.getResourceAsStream(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();
}
 
mTextView.setText(res);
}
//按钮事件响应
public void onClick(View v) {
if (v == mButton1){
createXmlFile();
} else if (v == mButton2){
domParseXML();
} else if (v == mButton3){
xmlPullParseXML();
}
}
}


第四步:由于我们在Sd卡上新建了文件,需要增加权限,如下代码(第16行):

代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
<?xml version= "1.0" encoding= "utf-8" ?>
<manifest xmlns:android= "http://schemas.android.com/apk/res/android"
package = "com.tutor.xml"
android:versionCode= "1"
android:versionName= "1.0" >
<application android:icon= "@drawable/icon" android:label= "@string/app_name" >
<activity android:name= ".XmlDemo"
android:label= "@string/app_name" >
<intent-filter>
<action android:name= "android.intent.action.MAIN" />
<category android:name= "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion= "7" />
<uses-permission android:name= "android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>

3.sax
SAX(simpleAPIforXML)是一种XML解析的替代方法.相比于DOM,SAX是一种速度更快,更有效的方法.它逐行扫描文档,一边扫描一边解析.而且相比于DOM,SAX可以在解析文档的任意时刻停止解析,但任何事物都有其相反的一面,对于SAX来说就是操作复杂.

  下面对resources.xml文件进行解析

       1、源文件如下

java代码:
  1. <resources>
  2. <resource>
  3. <mp3.name>kong</mp3.name>
  4. <mp3.author>侧田</mp3.author>
  5. </resource>
  6. <resource>
  7. <mp3.name>蚂蚁</mp3.name>
  8. <mp3.author>古巨基</mp3.author>
  9. </resource>
  10. </resources>

复制代码

       2、创建Mp3Info.java实体bean类

java代码:
  1. public class Mp3Info {
  2. private String mp3Name;
  3. private String author;
  4. public Mp3Info() {
  5. }
  6. public Mp3Info(String mp3Name, String author) {
  7. super();
  8. this.mp3Name = mp3Name;
  9. this.author = author;
  10. }
  11. public String getMp3Name() {
  12. return mp3Name;
  13. }
  14. public void setMp3Name(String mp3Name) {
  15. this.mp3Name = mp3Name;
  16. }
  17. public String getAuthor() {
  18. return author;
  19. }
  20. public void setAuthor(String author) {
  21. this.author = author;
  22. }
  23. @Override
  24. public String toString() {
  25. return "Mp3Info [author=" + author + ", mp3Name=" + mp3Name + "]";
  26. }
  27. }

复制代码

       3、创建Mp3ListContentHandler.java类,继承DefaultHandler类

java代码:
  1. import java.util.List;
  2. import org.xml.sax.Attributes;
  3. import org.xml.sax.SAXException;
  4. import org.xml.sax.helpers.DefaultHandler;
  5. public class Mp3ListContentHandler extends DefaultHandler {
  6. private Mp3Info mp3Info = null;
  7. private List<Mp3Info> mp3Infos = null;
  8. private String tagName = null;
  9. public Mp3ListContentHandler() {
  10. super();
  11. }
  12. public Mp3ListContentHandler(List<Mp3Info> mp3Infos) {
  13. super();
  14. this.mp3Infos = mp3Infos;
  15. }
  16. public List<Mp3Info> getMp3Infos() {
  17. return mp3Infos;
  18. }
  19. public void setMp3Infos(List<Mp3Info> mp3Infos) {
  20. this.mp3Infos = mp3Infos;
  21. }
  22. @Override
  23. public void startDocument() throws SAXException {
  24. // TODO Auto-generated method stub
  25. super.startDocument();
  26. }
  27. @Override
  28. public void startElement(String uri, String localName, String qName,
  29. Attributes attributes) throws SAXException {
  30. // TODO Auto-generated method stub
  31. tagName = localName;
  32. if (tagName.equals("resource")) {
  33. mp3Info = new Mp3Info();
  34. }
  35. }
  36. @Override
  37. public void characters(char[] ch, int start, int length)
  38. throws SAXException {
  39. // TODO Auto-generated method stub
  40. String tmp = new String(ch, start, length);
  41. if (tagName.equals("mp3.name")) {
  42. mp3Info.setMp3Name(tmp);
  43. } else if (tagName.equals("mp3.author")) {
  44. mp3Info.setAuthor(tmp);
  45. }
  46. }
  47. @Override
  48. public void endDocument() throws SAXException {
  49. // TODO Auto-generated method stub
  50. super.endDocument();
  51. }
  52. @Override
  53. public void endElement(String uri, String localName, String qName)
  54. throws SAXException {
  55. // TODO Auto-generated method stub
  56. tagName = localName;
  57. if (tagName.equals("resource")) {
  58. mp3Infos.add(mp3Info);
  59. }
  60. tagName = "";
  61. }
  62. }

复制代码

       4、创建TestSAXActivity.java类

java代码:
  1. import java.io.StringReader;
  2. import java.util.ArrayList;
  3. import java.util.Iterator;
  4. import java.util.List;
  5. import javax.xml.parsers.SAXParserFactory;
  6. import org.xml.sax.InputSource;
  7. import org.xml.sax.XMLReader;
  8. import android.app.Activity;
  9. import android.os.Bundle;
  10. import android.widget.LinearLayout;
  11. import android.widget.TextView;
  12. public class TestSAXActivity extends Activity {
  13. /** Called when the activity is first created. */
  14. private String xml = "<resources><resource><mp3.name>kong</mp3.name><mp3.author>侧田</mp3.author></resource><resource><mp3.name>蚂蚁</mp3.name><mp3.author>古巨基</mp3.author></resource></resources>";
  15. private LinearLayout layout = null;
  16. private TextView tv = null;
  17. @Override
  18. public void onCreate(Bundle savedInstanceState) {
  19. super.onCreate(savedInstanceState);
  20. setContentView(R.layout.main);
  21. layout = (LinearLayout) this.findViewById(R.id.main);
  22. List<Mp3Info> infos = parseXml(xml);
  23. String text = null;
  24. for (Iterator i = infos.iterator(); i.hasNext();) {
  25. Mp3Info mp3 = (Mp3Info) i.next();
  26. text = "" + mp3.getMp3Name() + " 演唱:"
  27. + mp3.getAuthor();
  28. tv = new TextView(this);
  29. tv.setText(text);
  30. tv.setWidth(500);
  31. tv.setTextSize(20);
  32. layout.addView(tv);
  33. }
  34. }
  35. public List<Mp3Info> parseXml(String xmlStr) {
  36. // 创建SAXParserFactory解析器工厂
  37. SAXParserFactory parserFactory = SAXParserFactory.newInstance();
  38. List<Mp3Info> mp3Infos = null;
  39. Mp3Info mp3Info = null;
  40. try {
  41. // 创建XMLReader对象,xml文件解析器
  42. XMLReader xmlReader = parserFactory.newSAXParser().getXMLReader();
  43. mp3Infos = new ArrayList<Mp3Info>();
  44. // 注册内容事件处理器(设置xml文件解析器的解析方式)
  45. xmlReader.setContentHandler(new Mp3ListContentHandler(mp3Infos));
  46. // 开始解析xml格式文件
  47. xmlReader.parse(new InputSource(new StringReader(xmlStr)));
  48. for (Iterator iterator = mp3Infos.iterator(); iterator.hasNext();) {
  49. mp3Info = (Mp3Info) mp3Infos.iterator();
  50. }
  51. mp3Infos.add(mp3Info);
  52. } catch (Exception e) {
  53. e.printStackTrace();
  54. }
  55. return mp3Infos;
  56. }
  57. }

复制代码

你可能感兴趣的:(Android 中创建与解析XML的方法)