JAXB实现XML和Bean互相转换

基于JAXB实现xml与bean的互相转换

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

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

/**
 * XmlParseUtil, 基于JAXB(Java And XML Binding)的xml,javabean互转工具类
 */	
public class XmlParseUtil {

	/**
	 * xmlToBean
	 */
	public static Object xmlToBean(String xmlstr, Class<?> load) throws JAXBException, IOException {
		JAXBContext context = JAXBContext.newInstance(load);
		Unmarshaller unmarshaller = context.createUnmarshaller();
		Object object = unmarshaller.unmarshal(new StringReader(xmlstr));
		return object;
	}

	/**
	 * beanToXml
	 */
	public static String beanToXml(Object obj, Class<?> load) throws JAXBException, IOException {
		JAXBContext context = JAXBContext.newInstance(load);
		Marshaller marshaller = context.createMarshaller();
		// 去报文头
		marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
		StringWriter writer = new StringWriter();
		CDataContentHandler cc = new CDataContentHandler(writer);
		marshaller.marshal(obj, cc);
		return writer.toString();
	}
	
}

CDataContentHandler.java

package com.panpass.common.util;

import java.io.IOException;
import java.io.Writer;
import java.util.regex.Pattern;

import org.dom4j.io.XMLWriter;
import org.xml.sax.SAXException;

/**
 * 处理CDATA[]
 *
 * @author cl
 * @since 2017年11月24日-上午1:03:39
 */
public class CDataContentHandler extends XMLWriter {

	public CDataContentHandler(Writer writer) throws IOException {
		super(writer);
	}
	
	// see http://www.w3.org/TR/xml/#syntax
	private static final Pattern XML_CHARS = Pattern.compile("[<>&]");

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
//		boolean useCData = XML_CHARS.matcher(new String(ch, start, length)).find();
		boolean useCData = true;
		if (useCData) {
			super.startCDATA();
		}
		super.characters(ch, start, length);
		if (useCData) {
			super.endCDATA();
		}
	}

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值