DOM方式解析xml是先把xml文档都读到内存中,然后再用DOM API来访问树形结构,并获取数据的。DOM比较符合人的思维模式,但是其对内存的消耗比较大。

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical"    tools:context=".MainActivity" >    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:id="@+id/textview01" /></LinearLayout>
View Code

在assets目录下添加product.xml文件

<?xml version="1.0" encoding="UTF-8"?><products>    <product name="黑茶" length="115">        <introducton>因产自中国湖南安化县而得名。是中国古代名茶之一,上个世纪50年代曾一度绝产,以至于默默无名。2010年,湖南黑茶走进中国上海世博会,成为中国世博会十大名茶之一。安化黑茶再度走进茶人的视野,成为茶人的新宠。其特色的千两茶,堪称一绝。<br/>           </introducton>        <imageurl>            http://baike.baidu.com/view/2255732.htm        </imageurl>    </product>    <product name="擂茶" length="109">        <introducton>起于汉、盛于明清的地方擂茶至今在湖南中部以北的安化一带传袭。其色味、功效、制作方法,以及饮茶习俗等,无不让途经于此的人感受到山乡古朴浓郁的擂茶文化。春暖花开的四月,记者跟随“环行洞庭湖”采访团走进了这个擂茶飘香的地方。<br/>                   </introducton>        <imageurl>            http://baike.baidu.com/view/66985.htm        </imageurl>    </product></products>
View Code

创建Product类

/** *  */package com.hyzhou.domxml2;import java.io.Serializable;/** * @author hyzhou * * 2013-8-29 */public class Product implements Serializable {    /**     *      */    private static final long serialVersionUID = -6907670870626810002L;    private int length;    private String introducton;    private String imageurl;    private String name;    public int getLength() {        return length;    }    public void setLength(int length) {        this.length = length;    }    public String getIntroducton() {        return introducton;    }    public void setIntroducton(String introducton) {        this.introducton = introducton;    }    public String getImageurl() {        return imageurl;    }    public void setImageurl(String imageurl) {        this.imageurl = imageurl;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    }
View Code

创建MainActivity类,用于解析XML并显示结果

package com.hyzhou.domxml2;import java.io.InputStream;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.NodeList;import android.os.Bundle;import android.util.Log;import android.widget.TextView;import android.app.Activity;public class MainActivity extends Activity {    private TextView    textView ;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        textView=(TextView)findViewById(R.id.textview01);         StringBuffer sb=new StringBuffer();            ArrayList<Product> list=    (ArrayList<Product>) getProductFromXml("product.xml");            Iterator<Product> it=list.iterator();         while(it.hasNext())         {          Product myit=it.next();          sb.append(myit.getName()+"        长度:"+myit.getLength()+"\n"+myit.getImageurl() +"\n"+myit.getIntroducton()+"\n\n");         }         Log.i("wa~~~~~",sb.toString());         textView.setText(sb.toString());    }    public List<Product> getProductFromXml(String fileName)    {        List<Product> products=new ArrayList<Product>();        DocumentBuilderFactory factory=null;         DocumentBuilder builder=null;         Document document=null;         InputStream inputStream=null;         //创建实例DocumentBuilderFactory         factory=DocumentBuilderFactory.newInstance();         try {            //创建DocumentBuilder               builder=factory.newDocumentBuilder();               //获取输入流               inputStream=this.getResources().getAssets().open(fileName);               Log.i("inputStream", inputStream.toString());               //加载XML文档               document=builder.parse(inputStream);             //找到根元素               Element root=document.getDocumentElement();               NodeList nodes=root.getElementsByTagName("product");                              //遍历所有子结点               Product myproduct=null;               for(int i=0;i<nodes.getLength();i++)               {                myproduct =new Product();                //得到第一个根节点product                Element productElement=(Element) nodes.item(i);                     //获取根节点的属性name和length                myproduct.setName(productElement.getAttribute("name"));                myproduct.setLength(Integer.parseInt(productElement.getAttribute("length")));                //获取子节点imageulr和introduction                Element introduction =(Element) productElement.getElementsByTagName("introducton").item(0);                myproduct.setIntroducton(introduction.getTextContent().trim());                Element imageurl=(Element) productElement.getElementsByTagName("imageurl").item(0);                myproduct.setImageurl(imageurl.getTextContent().trim());                //把得到的元素加入到List里面                products.add(myproduct);               }               inputStream.close();        } catch (Exception e) {            // TODO: handle exception            e.printStackTrace();        }        return products;            }        }
View Code

参考文档:http://www.cnblogs.com/zhangdongzi/archive/2011/04/14/2016434.html

更多相关文章

  1. Android(安卓)IQ包 发送 基于XMPP
  2. Weex Android(安卓)返回键 页面传值 生命周期
  3. AndroidManifest.xml文件剖析 (一)
  4. Android(安卓)Studio Gradle使用笔记
  5. Android动态加载View的几种方法
  6. 【Android】获取应用程序(包)的信息-----PackageManager的使用(
  7. 应用程序Manifest介绍
  8. Android(安卓)DataBinding使用详解
  9. 将tensorflow训练好的模型移植到Android(安卓)(MNIST手写数字识

随机推荐

  1. Android(安卓)studio 新建项目后报错:Coul
  2. Android(安卓)AsyncTask
  3. 在Android程序中使用全局变量
  4. Android中Bundle的使用示例
  5. Android核心分析(21)----Android应用框架之
  6. Android入门教程(四)之------Android工程
  7. android 截取头像
  8. 浅入浅出 Android(安卓)安全:第二章 Andro
  9. Android开机动画过程
  10. Android视频播放程序关键部分简要解析