xml转换

import java.io.ByteArrayInputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.ibatis.reflection.wrapper.CollectionWrapper;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;


public class JaxbUtil {

    @SuppressWarnings("rawtypes")
    private static ConcurrentMap<Class, JAXBContext> jaxbContexts = new ConcurrentHashMap<Class, JAXBContext>();

    /**
     * 将对象直接转换成String类型的 XML输出
     */
    public static String convertToXml(Object clazz, String encoding) {
        // 创建输出流
        StringWriter sw = new StringWriter();
        try {
            // 利用jdk中自带的转换类实现
            JAXBContext context = JAXBContext.newInstance(clazz.getClass());

            Marshaller marshaller = context.createMarshaller();
            // 格式化xml输出的格式
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
                    Boolean.TRUE);
            if (StringUtils.isNotBlank(encoding)) {
                marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
            }
            // 将对象转换成输出流形式的xml
            marshaller.marshal(clazz, sw);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return sw.toString();
    }

    /**
     * 创建UnMarshaller.
     * 线程不安全,需要每次创建或pooling。
     */
    @SuppressWarnings("rawtypes")
    public static Unmarshaller createUnmarshaller(Class clazz) {
        try {
            JAXBContext jaxbContext = getJaxbContext(clazz);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            return jaxbContext.createUnmarshaller();
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return null;
    }

    @SuppressWarnings("rawtypes")
    protected static JAXBContext getJaxbContext(Class clazz) {
        Validate.notNull(clazz, "'clazz' must not be null");
        JAXBContext jaxbContext = jaxbContexts.get(clazz);
        if (jaxbContext == null) {
            try {
                jaxbContext = JAXBContext.newInstance(clazz, CollectionWrapper.class);
                jaxbContexts.putIfAbsent(clazz, jaxbContext);
            } catch (JAXBException ex) {
                throw new RuntimeException("Could not instantiate JAXBContext for class [" + clazz + "]: "
                        + ex.getMessage(), ex);
            }
        }
        return jaxbContext;
    }

    /**
     * Xml->Java Object.
     */
    @SuppressWarnings("unchecked")
    public static <T> T fromXml(String xml, Class<T> clazz) {
        try {
            StringReader reader = new StringReader(xml);
            return (T) createUnmarshaller(clazz).unmarshal(reader);
        } catch (JAXBException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
    
    
    /**
     * 因单笔请求,只需取最后一条记录;如果是批量请求,最终获取结果需封装list集合批量展示
     * @param xml
     * @param clazz
     * @param elementName 节点名称
     * @return
     */
    @SuppressWarnings("rawtypes")
	public static HashMap<String, Object> fromSecondXml(String xml, Class clazz, String elementName) {

        HashMap<String, Object> stringHashMap = new HashMap<String, Object>();
        SAXReader reader = new SAXReader();
        try {
            org.dom4j.Document doc = reader.read(new ByteArrayInputStream(xml
                    .getBytes("GBK")));
            org.dom4j.Element Result = doc.getRootElement();//根节点
            org.dom4j.Element element;//子节点

            //获取对象属性名称数组
            Field[] fields = clazz.getDeclaredFields();
            String attributeValue = "";
            for (int j = 0; j < fields.length; j++) {
                for (Iterator i = Result.elementIterator(elementName); i.hasNext(); ) {
                    element = (org.dom4j.Element) i.next();
                    //该属性名相对于的节点内容
                    attributeValue = element.elementText(fields[j].getName());
                    //封装到map中
                    stringHashMap.put(fields[j].getName(),element.elementText(fields[j].getName()));
                }
                if (attributeValue == null || "".equalsIgnoreCase(attributeValue))
                    stringHashMap.put(fields[j].getName(),Result.elementText(fields[j].getName()));
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        return stringHashMap;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值