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布局文件,代码如下:

  1. <?xmlversion= "1.0" encoding= "utf-8" ?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. >
  7. <Button
  8. android:id="@+id/btn1"
  9. 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>
<?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,代码如下:

  1. package com.tutor.xml;
  2. import java.io.File;
  3. import java.io.FileNotFoundException;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import javax.xml.parsers.DocumentBuilder;
  7. import javax.xml.parsers.DocumentBuilderFactory;
  8. import javax.xml.parsers.ParserConfigurationException;
  9. import org.w3c.dom.Document;
  10. import org.w3c.dom.Element;
  11. import org.w3c.dom.NodeList;
  12. import org.xml.sax.SAXException;
  13. import org.xmlpull.v1.XmlPullParser;
  14. import org.xmlpull.v1.XmlPullParserException;
  15. import org.xmlpull.v1.XmlPullParserFactory;
  16. import org.xmlpull.v1.XmlSerializer;
  17. import android.app.Activity;
  18. import android.os.Bundle;
  19. import android.util.Log;
  20. import android.util.Xml;
  21. import android.view.View;
  22. import android.view.View.OnClickListener;
  23. import android.widget.Button;
  24. import android.widget.TextView;
  25. import android.widget.Toast;
  26. public class XmlDemo extends Activity implements OnClickListener{
  27. private static final StringBOOKS_PATH= "/sdcard/books.xml" ;
  28. private ButtonmButton1,mButton2,mButton3;
  29. private TextViewmTextView;
  30. @Override
  31. public void onCreate(BundlesavedInstanceState){
  32. super .onCreate(savedInstanceState);
  33. setContentView(R.layout.main);
  34. setupViews();
  35. }
  36. //初始化工作
  37. private void setupViews(){
  38. mTextView=(TextView)findViewById(R.id.result);
  39. mButton1=(Button)findViewById(R.id.btn1);
  40. mButton2=(Button)findViewById(R.id.btn2);
  41. mButton3=(Button)findViewById(R.id.btn3);
  42. mButton1.setOnClickListener(this );
  43. mButton2.setOnClickListener(this );
  44. mButton3.setOnClickListener(this );
  45. }
  46. //创建xml文件
  47. private void createXmlFile(){
  48. FilelinceseFile=new File(BOOKS_PATH);
  49. try {
  50. linceseFile.createNewFile();
  51. }catch (IOExceptione){
  52. Log.e("IOException" , "exceptionincreateNewFile()method" );
  53. }
  54. FileOutputStreamfileos=null ;
  55. try {
  56. fileos=new FileOutputStream(linceseFile);
  57. }catch (FileNotFoundExceptione){
  58. Log.e("FileNotFoundException" , "can'tcreateFileOutputStream" );
  59. }
  60. XmlSerializerserializer=Xml.newSerializer();
  61. try {
  62. serializer.setOutput(fileos,"UTF-8" );
  63. serializer.startDocument(null , true );
  64. serializer.startTag(null , "books" );
  65. for ( int i= 0 ;i< 3 ;i++){
  66. serializer.startTag(null , "book" );
  67. serializer.startTag(null , "bookname" );
  68. serializer.text("Android教程" +i);
  69. serializer.endTag(null , "bookname" );
  70. serializer.startTag(null , "bookauthor" );
  71. serializer.text("Frankie" +i);
  72. serializer.endTag(null , "bookauthor" );
  73. serializer.endTag(null , "book" );
  74. }
  75. serializer.endTag(null , "books" );
  76. serializer.endDocument();
  77. serializer.flush();
  78. fileos.close();
  79. }catch (Exceptione){
  80. Log.e("Exception" , "erroroccurredwhilecreatingxmlfile" );
  81. }
  82. Toast.makeText(getApplicationContext(),"创建xml文件成功!" ,Toast.LENGTH_SHORT).show();
  83. }
  84. //dom解析xml文件
  85. private void domParseXML(){
  86. Filefile=new File(BOOKS_PATH);
  87. DocumentBuilderFactorydbf=DocumentBuilderFactory.newInstance();
  88. DocumentBuilderdb=null ;
  89. try {
  90. db=dbf.newDocumentBuilder();
  91. }catch (ParserConfigurationExceptione){
  92. e.printStackTrace();
  93. }
  94. Documentdoc=null ;
  95. try {
  96. doc=db.parse(file);
  97. }catch (SAXExceptione){
  98. e.printStackTrace();
  99. }catch (IOExceptione){
  100. e.printStackTrace();
  101. }
  102. Elementroot=doc.getDocumentElement();
  103. NodeListbooks=root.getElementsByTagName("book" );
  104. Stringres="本结果是通过dom解析:" + "/n" ;
  105. for ( int i= 0 ;i<books.getLength();i++){
  106. Elementbook=(Element)books.item(i);
  107. Elementbookname=(Element)book.getElementsByTagName("bookname" ).item( 0 );
  108. Elementbookauthor=(Element)book.getElementsByTagName("bookauthor" ).item( 0 );
  109. res+="书名:" +bookname.getFirstChild().getNodeValue()+ "" +
  110. "作者:" +bookauthor.getFirstChild().getNodeValue()+ "/n" ;
  111. }
  112. mTextView.setText(res);
  113. }
  114. //xmlPullParser解析xml文件
  115. private void xmlPullParseXML(){
  116. Stringres="本结果是通过XmlPullParse解析:" + "/n" ;
  117. try {
  118. XmlPullParserFactoryfactory=XmlPullParserFactory.newInstance();
  119. XmlPullParserxmlPullParser=factory.newPullParser();
  120. xmlPullParser.setInput(Thread.currentThread().getContextClassLoader()
  121. .getResourceAsStream(BOOKS_PATH),"UTF-8" );
  122. int eventType=xmlPullParser.getEventType();
  123. try {
  124. while (eventType!=XmlPullParser.END_DOCUMENT){
  125. StringnodeName=xmlPullParser.getName();
  126. switch (eventType){
  127. case XmlPullParser.START_TAG:
  128. if ( "bookname" .equals(nodeName)){
  129. res+="书名:" +xmlPullParser.nextText()+ "" ;
  130. }else if ( "bookauthor" .equals(nodeName)){
  131. res+="作者:" +xmlPullParser.nextText()+ "/n" ;
  132. }
  133. break ;
  134. default :
  135. break ;
  136. }
  137. eventType=xmlPullParser.next();
  138. }
  139. }catch (IOExceptione){
  140. e.printStackTrace();
  141. }
  142. }catch (XmlPullParserExceptione){
  143. e.printStackTrace();
  144. }
  145. mTextView.setText(res);
  146. }
  147. //按钮事件响应
  148. public void onClick(Viewv){
  149. if (v==mButton1){
  150. createXmlFile();
  151. }else if (v==mButton2){
  152. domParseXML();
  153. }else if (v==mButton3){
  154. xmlPullParseXML();
  155. }
  156. }
  157. }
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行):

  1. <?xmlversion= "1.0" encoding= "utf-8" ?>
  2. <manifestxmlns:android="http://schemas.android.com/apk/res/android"
  3. package = "com.tutor.xml"
  4. android:versionCode="1"
  5. android:versionName="1.0" >
  6. <applicationandroid:icon="@drawable/icon" android:label= "@string/app_name" >
  7. <activityandroid:name=".XmlDemo"
  8. android:label="@string/app_name" >
  9. <intent-filter>
  10. <actionandroid:name="android.intent.action.MAIN" />
  11. <categoryandroid:name="android.intent.category.LAUNCHER" />
  12. </intent-filter>
  13. </activity>
  14. </application>
  15. <uses-sdkandroid:minSdkVersion="7" />
  16. <uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  17. </manifest>
<?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>

第五步:运行上述工程,查看效果:

启动首界面:

点击创建XML文件按钮,生成books.xml文件

books.xml内容如下:

  1. <?xmlversion= '1.0' encoding= 'UTF-8' standalone= 'yes' ?>
  2. <books>
  3. <book>
  4. <bookname>Android教程0 </bookname>
  5. <bookauthor>Frankie0</bookauthor>
  6. </book>
  7. <book>
  8. <bookname>Android教程1 </bookname>
  9. <bookauthor>Frankie1</bookauthor>
  10. </book>
  11. <book>
  12. <bookname>Android教程2 </bookname>
  13. <bookauthor>Frankie2</bookauthor>
  14. </book>
  15. </books>
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?> <books> <book> <bookname>Android教程0</bookname> <bookauthor>Frankie0</bookauthor> </book> <book> <bookname>Android教程1</bookname> <bookauthor>Frankie1</bookauthor> </book> <book> <bookname>Android教程2</bookname> <bookauthor>Frankie2</bookauthor> </book> </books>

点击DOM解析XML按钮:

点击XmlPullParse解析XML按钮:

Ok~今天就先讲到这里。thx~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值