Android Dom和XmlPullParse解析XML文件

采得百花成蜜后,为谁辛苦为谁甜。这篇文章主要讲述Android Dom和XmlPullParse解析XML文件相关的知识,希望能为你提供帮助。
Android Dom和XmlPullParse解析XML文件最近在在XML解析,测试了DOM和XmlPullParse两种模式解析XML,记录下来!
首先,创建在Sdcard里创建Xml文件,然后,建立两个按钮分别使用DOM、XmlPullParse来解析Xml文件,并且分别显示在TextView中.
废话少说,先上效果图:

Android Dom和XmlPullParse解析XML文件

文章图片

 
 
1,XmlPullParse使用基础: 1.1获取XmlPullParse
1 XmlPullParserFactory factory =XmlPullParserFactory.newInstance(); 2 XmlPullParser xmlPullParser =factory.newPullParser();

 
1.2 设置XmlPullParse解析器的输入
1this.getClass().getClassLoader(); 2xmlPullParser.setInput(ClassLoader.getSystemResourceAsStream(BOOKS_PATH),"UTF-8");

1.3  解析XML文档数据.其主要工作就是调用XmlPullParser.next()获取数据,然后再调用XmlPullParser.getEventType()得到当前解析状态再做相应的处理
1 int eventType = parser.getEventType(); //返回的状态类型 2 if (eventType == XmlPullParser.START_DOCUMENT) //XML文档开始 3 if (eventType == XmlPullParser.START_TAG) //开始读取某个标签 4 if (eventType == XmlPullParser.END_TAG) //结束读取某个标签 5 //TEXT:Text内容 6 if (eventType == XmlPullParser.END_DOCUMENT) //XML文档结束

  2.布局文件,三个Button,两个TextView,代码如下:
1 < ?xml version="1.0" encoding="utf-8"?> 2 < LinearLayout 3xmlns:android="http://schemas.android.com/apk/res/android" 4android:layout_width="match_parent" 5android:layout_height="match_parent" 6android:orientation="vertical"> 7 8< Button 9android:id="@+id/create_xml" 10android:layout_width="match_parent" 11android:layout_height="40dp" 12android:text="创建XML文件"/> 13 14< Button 15android:id="@+id/dom_xml" 16android:layout_width="match_parent" 17android:layout_height="40dp" 18android:text="DOM解析XML"/> 19 20< Button 21android:id="@+id/pull_xml" 22android:layout_width="match_parent" 23android:layout_height="40dp" 24android:text="XmlPullParse解析XML"/> 25 26< TextView 27android:id="@+id/dom_text" 28android:layout_width="match_parent" 29android:layout_height="wrap_content" 30android:textColor="@color/colorAccent" 31android:textSize="18dip"/> 32 33< TextView 34android:id="@+id/pull_text" 35android:layout_width="match_parent" 36android:layout_height="wrap_content" 37android:textColor="@color/colorPrimary" 38android:textSize="18dip"/> 39 40 < /LinearLayout>

 
3.主Activity:创建Xml文件,和Dom和XmlPullParse解析XMlL,代码如下:
1 package com.zwl.xmlparseproject; 2 3 import android.app.Activity; 4 import android.support.v7.app.AppCompatActivity; 5 import android.os.Bundle; 6 import android.util.Log; 7 import android.util.Xml; 8 import android.view.View; 9 import android.widget.Button; 10 import android.widget.TextView; 11 import android.widget.Toast; 12 13 import org.w3c.dom.Document; 14 import org.w3c.dom.Element; 15 import org.w3c.dom.Node; 16 import org.w3c.dom.NodeList; 17 import org.xml.sax.SAXException; 18 import org.xmlpull.v1.XmlPullParser; 19 import org.xmlpull.v1.XmlPullParserException; 20 import org.xmlpull.v1.XmlPullParserFactory; 21 import org.xmlpull.v1.XmlSerializer; 22 23 import java.io.File; 24 import java.io.FileNotFoundException; 25 import java.io.FileOutputStream; 26 import java.io.IOException; 27 28 import javax.xml.parsers.DocumentBuilder; 29 import javax.xml.parsers.DocumentBuilderFactory; 30 import javax.xml.parsers.ParserConfigurationException; 31 32 public class MainActivity extends Activity implements View.OnClickListener { 33 34private static final String TAG = MainActivity.class.getSimpleName(); 35private static final String BOOKS_PATH ="/sdcard/books.xml"; //创建books.xml文件路径 36private Button mCreateXml,mDomXml,mPullXml; 37private TextView mDemoText,mPullText; 38 39@Override 40protected void onCreate(Bundle savedInstanceState) { 41super.onCreate(savedInstanceState); 42setContentView(R.layout.activity_main); 43setupViews(); 44} 45 46private void setupViews() { 47mCreateXml =findViewById(R.id.create_xml); 48mDomXml =findViewById(R.id.dom_xml); 49mPullXml =findViewById(R.id.pull_xml); 50mDemoText =findViewById(R.id.dom_text); 51mPullText =findViewById(R.id.pull_text); 52mCreateXml.setOnClickListener(this); 53mDomXml.setOnClickListener(this); 54mPullXml.setOnClickListener(this); 55} 56 57@Override 58public void onClick(View v) { 59switch (v.getId()){ 60case R.id.create_xml: 61Log.d(TAG,"create_xml"); 62createXml(); 63break; 64case R.id.dom_xml: 65Log.d(TAG,"dom_xml"); 66domParseXML(); 67break; 68case R.id.pull_xml: 69Log.d(TAG,"pull_xml"); 70xmlPullParseXML(); 71break; 72default: 73break; 74} 75} 76 77//xmlPullParse解析Xml 78private void xmlPullParseXML() { 79String res="本结果通过XmlPullParse解析:"+"\\n"; 80try{ 81XmlPullParserFactory factory =XmlPullParserFactory.newInstance(); 82XmlPullParser xmlPullParser =factory.newPullParser(); 83this.getClass().getClassLoader(); 84xmlPullParser.setInput(ClassLoader.getSystemResourceAsStream(BOOKS_PATH),"UTF-8"); 85int eventType =xmlPullParser.getEventType(); 86try { 87while (eventType!=XmlPullParser.END_DOCUMENT){ 88String nodename =xmlPullParser.getName(); 89switch (eventType){ 90case XmlPullParser.START_TAG: 91if ("bookname".equals(nodename)){ 92res += "书名:"+xmlPullParser.nextText()+""; 93}else if ("bookauthor".equals(nodename)){ 94res +="作者:"+xmlPullParser.nextText()+"\\n"; 95} 96break; 97default: 98break; 99} 100eventType =xmlPullParser.next(); 101} 102} catch (IOException e) { 103e.printStackTrace(); 104} 105} catch (XmlPullParserException e) { 106e.printStackTrace(); 107} 108mPullText.setText(res); 109Toast.makeText(MainActivity.this, "XmlPullParser解析成功", Toast.LENGTH_SHORT).show(); 110} 111 112//dom解析XML文件 113private void domParseXML() { 114File file=new File(BOOKS_PATH); 115DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance(); 116DocumentBuilder db =null; 117try{ 118db =dbf.newDocumentBuilder(); 119} catch (ParserConfigurationException e) { 120e.printStackTrace(); 121} 122Document document =null; 123try{ 124document =db.parse(file); 125} catch (SAXException e) { 126e.printStackTrace(); 127} catch (IOException e) { 128e.printStackTrace(); 129} 130Element root =document.getDocumentElement(); 131NodeList books =root.getElementsByTagName("book"); 132String res ="本结果是通过dom解析的:"+"\\n"; 133for (int i=0 ; i< books.getLength(); i++){ 134Node book = books.item(i); 135Node bookname=((org.w3c.dom.Element) book).getElementsByTagName("bookname").item(0); 136Node bookauthor=((org.w3c.dom.Element) book).getElementsByTagName("bookauthor").item(0); 137res += "书名:"+bookname.getFirstChild().getNodeValue()+""+ 138"作者:"+bookauthor.getFirstChild().getNodeValue()+"\\n"; 139} 140mDemoText.setText(res); 141Toast.makeText(MainActivity.this, "解析成功", Toast.LENGTH_SHORT).show(); 142} 143 144//创建XML文件 145private void createXml() { 146File file =new File(BOOKS_PATH); 147try{ 148file.createNewFile(); 149} catch (IOException e) { 150e.printStackTrace(); 151Toast.makeText(MainActivity.this, "exception in createnewfile() method", Toast.LENGTH_SHORT).show(); 152} 153FileOutputStream fileOutputStream = null; 154try { 155fileOutputStream =new FileOutputStream(file); 156} catch (FileNotFoundException e) { 157e.printStackTrace(); 158Toast.makeText(MainActivity.this, "can\'t create file fileoutputStream", Toast.LENGTH_SHORT).show(); 159} 160XmlSerializer serializer = Xml.newSerializer(); 161try { 162serializer.setOutput(fileOutputStream,"UTF-8"); 163serializer.startDocument(null,true); 164serializer.startTag(null,"books"); 165for (int i=0 ; i< 3; i++){ 166serializer.startTag(null,"book"); 167serializer.startTag(null,"bookname"); 168serializer.text("Android测试"+i); 169serializer.endTag(null,"bookname"); 170serializer.startTag(null,"bookauthor"); 171serializer.text("xiaoshu"+i); 172serializer.endTag(null,"bookauthor"); 173serializer.endTag(null,"book"); 174} 175serializer.endTag(null,"books"); 176serializer.endDocument(); 177serializer.flush(); 178fileOutputStream.close(); 179} catch (IOException e) { 180e.printStackTrace(); 181} 182Toast.makeText(MainActivity.this, "创建xml文件成功", Toast.LENGTH_SHORT).show(); 183} 184 }

 
4. 由于我们在Sd卡上新建了文件,需要在AndroidManifest.xml里增加权限
1 < uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> //内外置SD卡写权限

 
完毕,全部代码如上.
【Android Dom和XmlPullParse解析XML文件】 

    推荐阅读