Android Dom和XmlPullParse解析XML文件

Posted 东慕雨

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android Dom和XmlPullParse解析XML文件相关的知识,希望对你有一定的参考价值。

Android Dom和XmlPullParse解析XML文件

最近在在XML解析,测试了DOM和XmlPullParse两种模式解析XML,记录下来!

首先,创建在Sdcard里创建Xml文件,然后,建立两个按钮分别使用DOM、XmlPullParse来解析Xml文件,并且分别显示在TextView中.

废话少说,先上效果图:

 

 

1,XmlPullParse使用基础:

1.1获取XmlPullParse

1 XmlPullParserFactory factory =XmlPullParserFactory.newInstance();
2 XmlPullParser xmlPullParser =factory.newPullParser();

 

1.2 设置XmlPullParse解析器的输入

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

虚拟DOM -------- 最易理解的解释

抱歉最近朋友结婚去浪了几天~未来几天会正常更新.今天带来XML文件解析

SpringSecurity-SAML(OpenSAML):无法解组断言:获取 org.w3c.dom.DOMException:WRONG_DOCUMENT_ERR

Android使用DOM生成和输出XML格式数据

Android之DOM解析XML

Android之DOM解析XML