欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SAX解析xml

程序员文章站 2022-05-28 08:02:32
...

继承DefaultHandler :
package com.mena.test;
import com.mena.domain.Reward;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.ArrayList;
import java.util.List;
/**
* @author Jun
* Sax解析实现DefaultHandler,重写startElement()和endElement()方法
*/
public class SaxParseHandle extends DefaultHandler {

private List<Reward> list = new ArrayList<>();

//实体类
private Reward reward;


/**
 * 解析xml
 * qName: 节点名
 * attributes: 节点中的属性集合
 */
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    //获取节点的各个属性
    if (qName.equals("ItemSpec")){
        reward = new Reward();
        reward.setId(attributes.getValue("id"));
        reward.setCircle(attributes.getValue("circle"));
        reward.setItem(attributes.getValue("item"));
        reward.setRate(attributes.getValue("rate"));
    }
}

/**
 *结束标签
 */
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
    //判断是否解析完一个节点
    if (qName.equals("ItemSpec")){
        list.add(reward);
        reward = null;
    }
}

public List<Reward> getList() {
    return list;
}

}

测试类:

package com.mena.test;
import com.mena.domain.Reward;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.util.List;

/**
* @author Jun
* 测试sax解析
*/
public class TestSax {

public static void main(String [] args) throws Exception{
    //获取SAXParseFactory实例
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    //通过saxParserFactory获取一个SAXParserFactory类的对象;
    SAXParser parser = saxParserFactory.newSAXParser();

    //创建SAXParserHandle对象(defaultHandler的实现类)
    SaxParseHandle handler = new SaxParseHandle();
    //解析xml
    parser.parse("src/reward.xml",handler);

    List<Reward> list = handler.getList();

    for (Reward reward : list){
        System.out.println(reward);
    }
}

}

相关标签: xml SAX