Android开发中解析xml的方法有哪些

这篇文章给大家介绍Android开发中解析xml的方法有哪些,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

创新互联是一家专注于成都网站设计、做网站与策划设计,梁平网站建设哪家好?创新互联做网站,专注于网站建设10余年,网设计领域的专业建站公司;建站业务涵盖:梁平等地区。梁平做网站价格咨询:18982081108

第一步:新建一个Android工程,命名为XmlDemo

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

<?xmlversion="1.0"encoding="utf-8"?>

  

第三步:修改主核心程序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);
  }
  // 创建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(),"创建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 ="本结果是通过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文件
  privatevoid xmlPullParseXML() {
    String res ="本结果是通过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 +="书名: " + 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);
  }
  // 按钮事件响应
  publicvoid onClick(View v) {
    if(v == mButton1) {
      createXmlFile();
    }else if(v == mButton2) {
      domParseXML();
    }else if(v == mButton3) {
      xmlPullParseXML();
    }
  }
}

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

<?xmlversion="1.0"encoding="utf-8"?>

  
    
      
        
        
      
    
  
  
  

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

启动首界面:

Android开发中解析xml的方法有哪些

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

Android开发中解析xml的方法有哪些

books.xml内容如下:

<?xmlversion='1.0'encoding='UTF-8'standalone='yes'?>

  
   Android教程0
   Frankie0
  
  
   Android教程1
   Frankie1
  
  
   Android教程2
   Frankie2
  

点击DOM解析XML按钮:

Android开发中解析xml的方法有哪些

点击XmlPullParse解析XML按钮:

Android开发中解析xml的方法有哪些

关于Android开发中解析xml的方法有哪些就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


当前文章:Android开发中解析xml的方法有哪些
分享URL:http://csdahua.cn/article/gecoeo.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流