用 Pull解析xml文件,报空指针异常,求大神求解!非常感谢!

package com.dream.pull;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.util.ArrayList;

import javax.management.modelmbean.XMLParseException;
import javax.xml.bind.annotation.XmlAttribute;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import com.dream.SAX.book;

public class Demo01 {

/**
 * @param args
 * @throws Exception 
 */
public static void main(String[] args) throws Exception {

    XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
    XmlPullParser parser = factory.newPullParser();
    //parser.setInput(new FileReader("teachers.xml"));
    parser.setInput(new FileInputStream("teachers.xml"),"utf-8");

    int eventType = parser.getEventType();

    ArrayList<Teacher> list = null;

    Teacher t = null;
    book b = null; 

    while (eventType != XmlPullParser.END_DOCUMENT) {
        String tag = parser.getName();
        switch (eventType) {
        case XmlPullParser.START_DOCUMENT:
            list = new ArrayList<>();
            break;
        case XmlPullParser.START_TAG:
            if ("teahcer".equals(tag)) {
                t = new Teacher();
                t.setBooks(new ArrayList<book>());
                int len = parser.getAttributeCount();
                for (int i = 0; i < len; i++) {
                    String key = parser.getAttributeName(i);
                    String value = parser.getAttributeValue(i);
                    if ("id".equals(key)) {
                        t.setId(value);
                    }else if ("classId".equals(key)) {
                        t.setClassId(value);
                    }
                }

            }else if ("name".equals(tag)) {
                t.setName(parser.nextText()); //这一行报空指针异常
            }else if ("age".equals(tag)) {
                t.setAge(Integer.parseInt(parser.nextText()));
            }else if ("sex".equals(tag)) {
                t.setSex(parser.nextText());
            }

            if ("book".equals(tag)) {
                b = new book();
            }else if ("bookName".equals(tag)) {
                b.setBookName(parser.nextText());
            }else if ("price".equals(tag)) {
                b.setPrice(parser.nextText());
            }

            break;
        case XmlPullParser.END_TAG:
            if ("teacher".equals(tag)) {
                list.add(t);
            }else if ("book".equals(tag)) {
                t.getBooks().add(b);
            }
            break;

        }
        eventType = parser.next();
    }
    System.out.println(list);

}   

}

1个回答

//这个是要解析的xml文件内容
<?xml version="1.0" encoding="UTF-8"?>


张三
18



Java从入门到精通
30


Android从入门到精通
50




李四
19



C++从入门到精通
30


C#从入门到精通
50



Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐