源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Android编程创建与解析xml的常用方法详解

  • 时间:2021-10-31 05:32 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Android编程创建与解析xml的常用方法详解
本文实例讲述了Android编程创建与解析xml的常用方法。分享给大家供大家参考,具体如下: 今天我今天给大家讲解一下Android创建xml以及一些解析xml的常用方法。 首先是创建,我们用XmlSerializer这个类来创建一个xml文件,其次是解析xml文件,常用的有dom,sax,XmlPullParser等方法,由于sax代码有点复杂,本节只讲解一下dom与XmlPullParser解析,sax我将会在下一节单独讲解,至于几种解析xml的优缺点我就不再讲述了。 为了方便理解,我做了一个简单的Demo。首先首界面有三个按钮,点击第一个按钮会在sdcard目录下创建一个books.xml文件。另外两个按钮分别是调用dom与XmlPullParser方法解析xml文件,并将结果显示在一个TextView里。大家可以按照我的步骤一步步来: [b]第一步:[/b]新建一个Android工程,命名为XmlDemo [b]第二步:[/b]修改main.xml布局文件,代码如下:
<?xmlversion="1.0"encoding="utf-8"?>
<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="创建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>

[b]第三步:[/b]修改主核心程序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();
    }
  }
}

[b]第四步:[/b]由于我们在Sd卡上新建了文件,需要增加权限,如下代码(第13行):
<?xmlversion="1.0"encoding="utf-8"?>
<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>

[b]第五步:[/b]运行上述工程,查看效果: 启动首界面: [img]http://files.jb51.net/file_images/article/201705/2017530112521321.jpg?2017430112547[/img] 点击创建XML文件按钮,生成books.xml文件 [img]http://files.jb51.net/file_images/article/201705/2017530112550970.jpg?201743011269[/img] books.xml内容如下:
<?xmlversion='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按钮: [img]http://files.jb51.net/file_images/article/201705/2017530112612403.jpg?2017430112640[/img] 点击XmlPullParse解析XML按钮: [img]http://files.jb51.net/file_images/article/201705/2017530112612403.jpg?2017430112640[/img] Ok~今天就先讲到这里。 [b]PS:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:[/b] [b]在线XML/JSON互相转换工具: [/b][url=http://tools.jb51.net/code/xmljson]http://tools.jb51.net/code/xmljson[/url] [b]在线格式化XML/在线压缩XML: [/b][url=http://tools.jb51.net/code/xmlformat]http://tools.jb51.net/code/xmlformat[/url] [b]XML[/b][b]在线压缩/格式化工具: [/b][url=http://tools.jb51.net/code/xml_format_compress]http://tools.jb51.net/code/xml_format_compress[/url] [b]XML[/b][b]代码在线格式化美化工具: [/b][url=http://tools.jb51.net/code/xmlcodeformat]http://tools.jb51.net/code/xmlcodeformat[/url] 更多关于Android相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/837.htm]Android操作XML数据技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/367.htm]Android编程之activity操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/423.htm]Android资源操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/325.htm]Android文件操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/410.htm]Android开发入门与进阶教程[/url]》、《[url=http://www.1sucai.cn/Special/375.htm]Android视图View技巧总结[/url]》及《[url=http://www.1sucai.cn/Special/124.htm]Android控件用法总结[/url]》 希望本文所述对大家Android程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部