sax解析xml通用工具类

1、xml

<?xml version="1.0" encoding="UTF-8"?>
<users>
    <user id="1">
        <name>毕向东</name>
        <password>bxd123</password>
    </user>
    <user id="2">
        <name>韩顺平</name>
        <password>hsp123</password>
    </user>
    <user id="3">
        <name>马士兵</name>
        <password>msb123</password>
    </user>
</users>

2、实体

package com.zzr.xml;

public class User {
    private String userId;
    private String name;
    private String password;


    @Override
    public String toString() {
        return "User{" +
                "userId=" + userId +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

3、解析器

package com.zzr.xml;

import org.apache.commons.lang3.StringUtils;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 赵志荣
 * @Description <p>用于解析xml为实体类的处理器  </P>
 * @version 1.0  
 */
class XMlHandler<T> extends DefaultHandler {
    String rootElemntName;
    Map<String, String> dataMap;
    StringBuilder stringBuilder;
    List<T> dataList;
    T data;
    Class<T> clz;
    private Map<String,Class> attrs;

    /**
     * @author 赵志荣
     * @Description <p> 当前标签名称 </P>
     * @version 1.0  
     */
    private String currentTag;
    /**
     * 要解析的单个实体的根元素名称
     * @param rootElemntName
     * @throws IllegalAccessException 
     * @throws InstantiationException 
     */
    XMlHandler(String rootElemntName,Class<T> clz,Map<String,Class> attrsMap) {
        this.rootElemntName = rootElemntName;
        this.clz = clz;
        this.attrs = attrsMap;
    }

    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
        dataMap = new HashMap<String, String>();
        stringBuilder = new StringBuilder();
        dataList = new ArrayList<T>();
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        // TODO Auto-generated method stub
        super.startElement(uri, localName, qName, attributes);
        //赋值给当前标签名称
        currentTag = qName;
        if (rootElemntName.equals(qName)) {
            try {
                data = clz.newInstance();

            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        //每次对一个标签解析前,都先置为空
        stringBuilder.setLength(0);
        //如果某个标签中有属性,则将其保存到map中,保存规则:key = “标签名称_属性名称” value = “属性值”
        if(attributes != null && dataMap != null){
            for (int i = 0; i < attributes.getLength(); i++) {
                dataMap.put(qName+attributes.getQName(i).substring(0,1).toUpperCase()+attributes.getQName(i).substring(1), attributes.getValue(i));
            }

        }


    }

    @Override
    public void characters(char[] ch, int start, int len) throws SAXException {
        // TODO Auto-generated method stub
        super.characters(ch, start, len);
        stringBuilder.append(ch,start,len);
        Field[] fields = clz.getDeclaredFields();
        try {
            if (StringUtils.isNotEmpty(currentTag) && data != null) {
                for (Field field : fields) {
                    String name = field.getName();
                    if (currentTag.equals(name)) {
                        name = name.substring(0,1).toUpperCase() + name.substring(1);

                        Method method = data.getClass().getMethod("set"+name, field.getType());
                        method.invoke(data, stringBuilder.toString());
                    }
                }
            }

        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        super.endElement(uri, localName, qName);
        if (rootElemntName.equals(qName)) {
            try {
                if (attrs != null) {

                    for (String attrName : attrs.keySet()) {
                        String methodName = "set"+attrName.substring(0,1).toUpperCase()+attrName.substring(1);
                        Method method = data.getClass().getMethod(methodName,attrs.get(attrName));
                        method.invoke(data, dataMap.get(attrName));
                    }
                }
            } catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            dataList.add(data);
        }

    }

    @Override
    public void endDocument() throws SAXException {
    System.out.println("解析结束:"+dataList);
        super.endDocument();
    }


    public List<T> getDataList(){
        return dataList;
    }

    public T getData(){
        return data;
    }
}

4、工具类

package com.zzr.xml;

import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by sjgtw-zzr on 2018/5/17.
 */
public class XmlParseUtils {

    /**
     *
     * @param inputStream  输入流
     * @param rootElementName 根标签
     * @param clazz bean的类
     * @param attrs 属性
     * @param <T> bean的泛型
     * @return
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws IOException
     */
    public static <T> List<T> getBeanListFromXml(InputStream inputStream, String rootElementName,Class<T> clazz, Map<String,Class> attrs) throws ParserConfigurationException, SAXException, IOException {
        // 加载文件返回文件的输入流
        XMlHandler<T> handler = new XMlHandler<T>(rootElementName,clazz,attrs);
        // 1. 得到SAX解析工厂
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        // 2. 让工厂生产一个sax解析器
        SAXParser newSAXParser = saxParserFactory.newSAXParser();
        // 3. 传入输入流和handler,解析
        newSAXParser.parse(inputStream, handler);
        inputStream.close();
        return handler.getDataList();
    }

    public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException {
        InputStream inputStream = new FileInputStream(new File("I:\\sjgtw-zzr\\zzr-demo\\zzr-test\\src\\main\\java\\users.xml"));
        String rootElementName = "user";
        Class clazz = User.class;
        Map<String,Class> dataMap = new HashMap<String, Class>();
        dataMap.put("userId",String.class);
        List<User> userList = getBeanListFromXml(inputStream,rootElementName,clazz,dataMap);
        for (User user: userList){
            System.out.println(user+"===================================");
        }
    }
}
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhaozhirongfree1111/article/details/80352793
个人分类: spring
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭