xml解析

Xml解析

package lee.service;   

  

import java.io.InputStream;   

import java.util.ArrayList;   

import java.util.List;   

import org.xmlpull.v1.XmlPullParser;   

import android.util.Xml;   

import lee.vo.Person;   

  

public class XMLPullService {   

       

    public List<Person> readXML(InputStream inStream) throws Exception{   

       

        List<Person> persons = null;   

           

        Person person = null;   

           

        XmlPullParser pullParser = Xml.newPullParser(); //获取Pull解析器 Xml.newPullParser()添加一个pullParser解析器带命名空间的支持   

           

        pullParser.setInput(inStream, "UTF-8");     //设置Pull解析器进行解析的XML内容   

           

        int event = pullParser.getEventType();      //获取第一个事件   

           

        while(event!=XmlPullParser.END_DOCUMENT)    //如果还不是结束文档事件,迭代每一个元素   

        {   

            switch (event)   

            {   

            case XmlPullParser.START_DOCUMENT:              //开始文档事件   

                persons = new ArrayList<Person>();   

                break;   

       

            case XmlPullParser.START_TAG:                   //开始元素事件   

                if("person".equals(pullParser.getName()))       //pullParser.getName()得到当前指针所指向的节点的名称   

                {   

                    person = new Person();   

                    int id = new Integer(pullParser.getAttributeValue(0));   

                    person.setId(id);   

                }   

                if(person!=null)   

                {   

                    if("name".equals(pullParser.getName()))   

                    {   

                        String name = pullParser.nextText();    //得到当前节点下一个文本节点的内容------>  <name>liming</name> 得到liming   

                        person.setName(name);   

                    }   

                    else if("age".equals(pullParser.getName()))   

                    {   

                        String age = pullParser.nextText(); //获取下一个Text类型节点的值   

                        person.setAge(new Short(age));   

                    }   

                }   

                break;   

            case XmlPullParser.END_TAG:                 //结束元素事件   

                if("person".equals(pullParser.getName()))   

                {   

                    persons.add(person);   

                    person = null;   

                }   

                break;   

            }   

            event = pullParser.next();                  //进入下一个元素并触发相应事件   

        }   

        return persons;   

    }   

}

第二种方式(较为复杂,用pullparser.Next()来进入下一个元素,用.textNext来返回当前String类型元素的值):

 

public class PullXmlActivity extends Activity{  

    private List<Book> list=null;  

    private PullXmlAdapter adapter;  

    private ListView lv;  

    @Override  

    protected void onCreate(Bundle savedInstanceState) {  

        // TODO Auto-generated method stub   

        super.onCreate(savedInstanceState);  

        setContentView(R.layout.listview);  

        lv=(ListView)findViewById(R.id.listView);  

        InputStream in;  

        try {  

            in = this.getAssets().open("books.xml");  

              

            list=pullxml(in);  

              

        } catch (IOException e) {  

            // TODO Auto-generated catch block   

            e.printStackTrace();  

        } catch (Exception e) {  

            // TODO Auto-generated catch block   

            e.printStackTrace();  

        }  

        adapter=new PullXmlAdapter(PullXmlActivity.this, list);   

        lv.setAdapter(adapter);  

    }  

    /**xml文件的获取

     * 1.xml文件放在res的xml文件夹下(推荐)使用XmlResourceParser xmlParser = this.getResources().getXml(R.xml.XXX);

     * 2.xml文件放在raw的xml文件夹下使用InputStream inputStream =this.getResources().openRawResource(R.raw.XXX);  

     * 3.xml文件放在assets文件夹下(本人测试发现通过此方法获取的XML文档不能带有首行:<?xml version="1.0" encoding="utf-8"?>,

     * 否则解析报错,具体原因未查明:InputStream inputStream = getResources().getAssets().open(fileName);

     * 4.xml文件放在SD卡, path路径根据实际项目修改,此次获取SDcard根目录:    

     * String path = Environment.getExternalStorageDirectory().toString();   

     * File xmlFlie = new File(path+fileName);   

     * InputStream inputStream = new FileInputStream(xmlFlie);   

     */  

    public List<Book> pullxml(InputStream in)throws Exception{  

        List<Book> list=null;  

        Book book = null;  

            // 由android.util.Xml创建一个XmlPullParser实例   

            XmlPullParser parser = Xml.newPullParser();  

            // 设置输入流 并指明编码方式   

               parser.setInput(in, "UTF-8");  

            // 产生第一个事件   

               int eventType = parser.getEventType();  

                 

               while (eventType != XmlPullParser.END_DOCUMENT) {  

                   switch (eventType) {  

                // 判断当前事件是否为文档开始事件   

                   case XmlPullParser.START_DOCUMENT:  

                       list=new ArrayList<Book>();// 初始化list集合   

                       break;  

                    // 判断当前事件是否为标签元素开始事件   

                   case XmlPullParser.START_TAG:  

                       if (parser.getName().equals("book")) { // 判断开始标签元素是否是book   

                           book = new Book();  

                       } else if (parser.getName().equals("id")) {  

                           eventType = parser.next();  

                           // 得到book标签的属性值,并设置book的id   

                            book.setId(Integer.parseInt(parser.getText()));  

                        } else if (parser.getName().equals("name")) { // 判断开始标签元素是否是book   

                             eventType = parser.next();  

                             book.setName(parser.getText());  

                        } else if (parser.getName().equals("price")) { // 判断开始标签元素是否是price   

                            eventType = parser.next();  

                             book.setPrice(Float.parseFloat(parser.getText()));  

                        }  

                       break;  

                    // 判断当前事件是否为标签元素结束事件   

                   case XmlPullParser.END_TAG:  

                       if (parser.getName().equals("book")) { // 判断结束标签元素是否是book   

                           list.add(book); // 将book添加到books集合   

                           book = null;  

                       }  

                       break;  

                   }  

                   // 进入下一个元素并触发相应事件   

                   eventType = parser.next();  

               }  

               return list;  

    }  

}

你可能感兴趣的:(xml解析)