Android開(kāi)發(fā)中解析xml的方法有哪些

這篇文章給大家介紹Android開(kāi)發(fā)中解析xml的方法有哪些,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。

創(chuàng)新互聯(lián)是一家專注于成都網(wǎng)站設(shè)計(jì)、做網(wǎng)站與策劃設(shè)計(jì),梁平網(wǎng)站建設(shè)哪家好?創(chuàng)新互聯(lián)做網(wǎng)站,專注于網(wǎng)站建設(shè)10余年,網(wǎng)設(shè)計(jì)領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:梁平等地區(qū)。梁平做網(wǎng)站價(jià)格咨詢:18982081108

第一步:新建一個(gè)Android工程,命名為XmlDemo

第二步:修改main.xml布局文件,代碼如下:

<&#63;xmlversion="1.0"encoding="utf-8"&#63;>
<LinearLayoutxmlns: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="創(chuàng)建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,代碼如下:

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 extendsActivity implementsOnClickListener {
  privatestatic final String BOOKS_PATH = "/sdcard/books.xml";
  privateButton mButton1, mButton2, mButton3;
  privateTextView mTextView;
  @Override
  publicvoid onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    setupViews();
  }
  // 初始化工作
  privatevoid 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);
  }
  // 創(chuàng)建xml文件
  privatevoid 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(),"創(chuàng)建xml文件成功!",
        Toast.LENGTH_SHORT).show();
  }
  // dom解析xml文件
  privatevoid 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 ="本結(jié)果是通過(guò)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 +="書(shū)名: " + bookname.getFirstChild().getNodeValue() +" "
          +"作者: " + bookauthor.getFirstChild().getNodeValue() +"/n";
    }
    mTextView.setText(res);
  }
  // xmlPullParser解析xml文件
  privatevoid xmlPullParseXML() {
    String res ="本結(jié)果是通過(guò)XmlPullParse解析:" + "/n";
    try{
      XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
      XmlPullParser xmlPullParser = factory.newPullParser();
      xmlPullParser.setInput(Thread.currentThread()
          .getContextClassLoader().getResourceAsStream(BOOKS_PATH),
          "UTF-8");
      inteventType = xmlPullParser.getEventType();
      try{
        while(eventType != XmlPullParser.END_DOCUMENT) {
          String nodeName = xmlPullParser.getName();
          switch(eventType) {
          caseXmlPullParser.START_TAG:
            if("bookname".equals(nodeName)) {
              res +="書(shū)名: " + 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);
  }
  // 按鈕事件響應(yīng)
  publicvoid onClick(View v) {
    if(v == mButton1) {
      createXmlFile();
    }else if(v == mButton2) {
      domParseXML();
    }else if(v == mButton3) {
      xmlPullParseXML();
    }
  }
}

第四步:由于我們?cè)赟d卡上新建了文件,需要增加權(quán)限,如下代碼(第13行):

<&#63;xmlversion="1.0"encoding="utf-8"&#63;>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
  package="com.tutor.xml"android:versionCode="1"android:versionName="1.0">
  <applicationandroid:icon="@drawable/icon"android:label="@string/app_name">
    <activityandroid:name=".XmlDemo"android:label="@string/app_name">
      <intent-filter>
        <actionandroid:name="android.intent.action.MAIN"/>
        <categoryandroid:name="android.intent.category.LAUNCHER"/>
      </intent-filter>
    </activity>
  </application>
  <uses-sdkandroid:minSdkVersion="7"/>
  <uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>

第五步:運(yùn)行上述工程,查看效果:

啟動(dòng)首界面:

Android開(kāi)發(fā)中解析xml的方法有哪些

點(diǎn)擊創(chuàng)建XML文件按鈕,生成books.xml文件

Android開(kāi)發(fā)中解析xml的方法有哪些

books.xml內(nèi)容如下:

<&#63;xmlversion='1.0'encoding='UTF-8'standalone='yes'&#63;>
<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>

點(diǎn)擊DOM解析XML按鈕:

Android開(kāi)發(fā)中解析xml的方法有哪些

點(diǎn)擊XmlPullParse解析XML按鈕:

Android開(kāi)發(fā)中解析xml的方法有哪些

關(guān)于Android開(kāi)發(fā)中解析xml的方法有哪些就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。

文章名稱:Android開(kāi)發(fā)中解析xml的方法有哪些
URL地址:http://muchs.cn/article40/gecoeo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供、關(guān)鍵詞優(yōu)化、網(wǎng)站營(yíng)銷、手機(jī)網(wǎng)站建設(shè)、動(dòng)態(tài)網(wǎng)站網(wǎng)站維護(hù)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站網(wǎng)頁(yè)設(shè)計(jì)