SAX解析XML文件-采用自定义布局

前端之家收集整理的这篇文章主要介绍了SAX解析XML文件-采用自定义布局前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1.新建saxxml项目

2.Foods.xml

<?xml version="1.0" encoding="UTF-8"?>
<foods>
    <food>
        <name>保定会馆1</name>
        <description>保定会馆,是一家百年老店,由chj创建。希望大家过去品尝.保定会馆,是一家百年老店,由chj创建。希望大家过去品尝.保定会馆,是一家百年老店,由chj创建。希望大家过去品尝.保定会馆,是一家百年老店,由chj创建。希望大家过去品尝.</description>
        <iprice>80</iprice>
        <price>148</price>
        <sum>1666人</sum>
        <url>lp</url>
    </food>
    <food>
        <name>保定会馆2</name>
        <description>保定会馆,是一家百年老店,由chj创建。希望大家过去品尝.</description>
        <iprice>78</iprice>
        <price>148</price>
        <sum>1666人</sum>
        <url>bz</url>
    </food>
    <food>
        <name>保定会馆3</name>
        <description>保定会馆,是一家百年老店,由chj创建。希望大家过去品尝.</description>
        <iprice>68</iprice>
        <price>148</price>
        <sum>1666人</sum>
        <url>food</url>
    </food>
    <food>
        <name>保定会馆4</name>
        <description>保定会馆,是一家百年老店,由chj创建。希望大家过去品尝.</description>
        <iprice>48</iprice>
        <price>148</price>
        <sum>1666人</sum>
        <url>bz</url>
    </food>
    <food>
        <name>保定会馆5</name>
        <description>保定会馆,是一家百年老店,由chj创建。希望大家过去品尝.</description>
        <iprice>18</iprice>
        <price>148</price>
        <sum>1666人</sum>
        <url>lp</url>
    </food>
    <food>
        <name>保定会馆6</name>
        <description>保定会馆,是一家百年老店,由chj创建。希望大家过去品尝.</description>
        <iprice>58</iprice>
        <price>148</price>
        <sum>1666人</sum>
        <url>food</url>
    </food>
</foods>

3.activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="${relativePackage}.${activityClass}" >
    <ListView  android:id="@+id/lv_foods" android:layout_width="match_parent" android:layout_height="match_parent" android:divider="#ee7600" android:dividerHeight="1px" >
    </ListView>
</RelativeLayout>

4.Item_food.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingTop="5dp" android:paddingBottom="5dp" android:gravity="center_vertical|center_horizontal" android:orientation="horizontal" >

    <!-- 图片 -->

    <ImageView  android:id="@+id/iv_icon" android:layout_width="100dp" android:layout_height="100dp" android:layout_marginLeft="10dp" android:src="@drawable/food" />

    <LinearLayout  android:layout_width="0dp" android:layout_height="100dp" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_weight="1" android:orientation="vertical" >

        <TextView  android:id="@+id/tv_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="保定会馆" />
        <!-- 少个空格 -->

        <TextView  android:id="@+id/tv_description" android:layout_width="wrap_content" android:layout_height="wrap_content" android:lineSpacingExtra="3dp" android:maxLines="3" android:ellipsize="end" android:text=" 保定会馆保定会馆保定会馆保定会馆保定会馆保定会馆保定会馆保定会馆保定会馆 " />

        <LinearLayout  android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" >

            <TextView  android:id="@+id/tv_iprice" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="58" android:textColor="#ff0000" android:textSize="18sp" android:textStyle="bold" />

            <TextView  android:id="@+id/tv_price" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="148" />

            <TextView  android:id="@+id/tv_sum" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="3" android:gravity="right" android:text="666666人" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>

5.Food.java

package com.example.domain;

public class Food {

    private String name;
    private String description;
    private double iprice;
    private double price;
    private String sum;

    // 加入显示图片URL地址
    private String url;

    public Food() {
        super();
        // TODO Auto-generated constructor stub
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public double getIprice() {
        return iprice;
    }

    public void setIprice(double iprice) {
        this.iprice = iprice;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getSum() {
        return sum;
    }

    public void setSum(String sum) {
        this.sum = sum;
    }

    @Override
    public String toString() {
        return "Food [name=" + name + ",description=" + description
                + ",iprice=" + iprice + ",price=" + price + ",sum=" + sum
                + "]";
    }

}

6.FoodAdapter.java

package com.example.adapter;

import java.util.List;

import android.content.Context;
import android.graphics.Paint;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.domain.Food;
import com.example.saxxml.R;

public class FoodAdapter extends BaseAdapter {

    private List<Food> data;
    private Context context;

    private ViewHolder viewHolder;

    public FoodAdapter(Context context,List<Food> data) {
        this.context = context;
        this.data = data;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position,View convertView,ViewGroup parent) {
        if (convertView == null) {
            // 创建绑定对象
            viewHolder = new ViewHolder();
            // 把一个文件转换成一个View对象
            convertView = View.inflate(context,R.layout.item_food,null);
            // 赋值
            viewHolder.tv_name = (TextView) convertView
                    .findViewById(R.id.tv_name);
            viewHolder.tv_description = (TextView) convertView
                    .findViewById(R.id.tv_description);
            viewHolder.tv_iprice = (TextView) convertView
                    .findViewById(R.id.tv_iprice);
            viewHolder.tv_price = (TextView) convertView
                    .findViewById(R.id.tv_price);
            // 文字中间添加横线
            viewHolder.tv_price.getPaint()
                    .setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            viewHolder.tv_sum = (TextView) convertView
                    .findViewById(R.id.tv_sum);
            viewHolder.iv_icon = (ImageView) convertView
                    .findViewById(R.id.iv_icon);
            // 附带数据
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        // 获取对象
        Food food = data.get(position);

        // 设置显示的文本
        viewHolder.tv_name.setText(food.getName());
        viewHolder.tv_description.setText(food.getDescription());
        viewHolder.tv_iprice.setText(food.getIprice() + "");
        viewHolder.tv_price.setText(food.getPrice() + "");
        viewHolder.tv_sum.setText(food.getSum());

        // 获取URL地址
        String url = food.getUrl();
        if ("lp".equals(url)) {
            // 把这个图片对应的图片 显示出来
            viewHolder.iv_icon.setImageResource(R.drawable.lp);
        } else if ("bz".equals(url)) {
            viewHolder.iv_icon.setImageResource(R.drawable.bz);
        } else {
            viewHolder.iv_icon.setImageResource(R.drawable.food);
        }
        // 返回当前条目对象
        return convertView;
    }

    // 绑定类
    class ViewHolder {
        public TextView tv_name,tv_description,tv_iprice,tv_price,tv_sum;
        public ImageView iv_icon;

    }

}

7.MainActivity.java

package com.example.saxxml;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.example.adapter.FoodAdapter;
import com.example.domain.Food;

public class MainActivity extends Activity {

    //声明显示的控件
    private ListView lv_foods;
    //声明显示的数据 model
    private List<Food> data = new ArrayList<Food>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取控件
        lv_foods = (ListView) findViewById(R.id.lv_foods);

        //解析出data数据
        try {
            parseXml();
            for(Food f:data){
                System.out.println(f);
            }
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //创建适配器对象
        ListAdapter adapter = new FoodAdapter(this,data);
        //设置显示的数据
        lv_foods.setAdapter(adapter);
    }


    //解析xml文件
    public void parseXml() throws ParserConfigurationException,SAXException,IOException{

        //1.首先获取sax解析工厂对象
        SAXParserFactory factory = SAXParserFactory.newInstance();
        //2.获取解析器对象
        SAXParser parser = factory.newSAXParser();
        //3.拿到解析的流
        InputStream is = getAssets().open("foods.xml");
        //4.解析xml文件
        parser.parse(is,new FoodHanlder());

    }


    //5.创建解析的类
    class FoodHanlder extends DefaultHandler{

        private boolean flag=false;

        private Food food;
        //记录标志名称
        private String tagName=null;
        //文档开始
        @Override
        public void startDocument() throws SAXException {
            //初始化集合
            super.startDocument();
        }


        //文档结束
        @Override
        public void endDocument() throws SAXException {
            super.endDocument();
        }

        //解析元素开始
        @Override
        public void startElement(String uri,String localName,String qName,Attributes attributes) throws SAXException {
            super.startElement(uri,localName,qName,attributes);
            if("food".equals(localName)){
                //创建一个实体bean对象
                 food = new Food();
            }else{
                tagName=localName;
            }
        }


        //解析元素结束
        @Override
        public void endElement(String uri,String qName)
                throws SAXException {
            // TODO Auto-generated method stub
            super.endElement(uri,qName);

            if("food".equals(localName)){
                //加入到集合中
                data.add(food);
                //设置为null
                food=null;
            }else{
                tagName=null;
            }
        }

        //获取元素中文内容
        @Override
        public void characters(char[] ch,int start,int length)
                throws SAXException {
            super.characters(ch,start,length);
            if(tagName!=null){
                String temp = new String(ch,length);
                if("name".equals(tagName)){
                    food.setName(temp);
                }else if("description".equals(tagName)){
                    food.setDescription(temp);
                }else if("iprice".equals(tagName)){
                    food.setIprice(Double.parseDouble(temp));
                }else if("price".equals(tagName)){
                    food.setPrice(Double.parseDouble(temp));
                }else if("sum".equals(tagName)){
                    food.setSum(temp);
                }else if("url".equals(tagName)){
                    food.setUrl(temp);
                }
            }
        }
    }
}

8.演示效果

@H_467_1403@ 原文链接:https://www.f2er.com/xml/296733.html

猜你在找的XML相关文章