基于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();
}
}
}