【开发心得】Xml转JavaBean
前言: 在JSON大行其道的今天,xml虽然重,但是因为更为严格,所谓还是有存在的价值的,而数据交互的时候,免不了JavaBean转xml或者xml转JavaBean。然后传统的解决方案就是直接使用dom4j,sax解析的方式,手动去get。这样会导致可读性变差,维护困难,是否有向json那样,有fastjson或者gson一类的工具可以用呢,答案是一定的。首先github上有一些类似fastxml之类的工具类,可以用,但是博主今天推荐的还是java1.6之后引入的jaxb
不写重复的帖子,引用的文章已经足够详细了
作为补充呢。博主给出工具类参考,可以上手即用。
package com.xxx.xxx;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;
import java.io.ByteArrayOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.StringReader;
/**
* 封装了XML转换成object,object转换成XML的代码
*/
@Slf4j
public class XMLUtil {
/**
* 将对象直接转换成String类型的 XML输出
*
* @param obj
* @return
*/
public static String convertToXml(Object obj) {
try {
String result;
JAXBContext context = JAXBContext.newInstance(obj.getClass());
XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
Boolean.TRUE);
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(baos, (String) marshaller.getProperty(Marshaller.JAXB_ENCODING));
marshaller.marshal(obj, xmlStreamWriter);
xmlStreamWriter.writeEndDocument();
xmlStreamWriter.close();
result = new String(baos.toByteArray());
}
return result;
} catch (Exception e) {
log.error("{}", e);
}
return null;
}
/**
* 将对象根据路径转换成xml文件
*
* @param obj
* @param path
* @return
*/
public static void convertToXml(Object obj, String path) {
try {
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
Boolean.TRUE);
try (FileWriter fw = new FileWriter(path)) {
marshaller.marshal(obj, fw);
}
} catch (Exception e) {
log.error("{}", e);
}
}
@SuppressWarnings("unchecked")
/**
* 将String类型的xml转换成对象
*/
public static Object convertXmlStrToObject(Class clazz, String xmlStr) {
Object xmlObject = null;
try {
JAXBContext context = JAXBContext.newInstance(clazz);
Unmarshaller unmarshaller = context.createUnmarshaller();
try (StringReader sr = new StringReader(xmlStr)) {
xmlObject = unmarshaller.unmarshal(sr);
}
} catch (Exception e) {
log.error("{}", e);
}
return xmlObject;
}
@SuppressWarnings("unchecked")
/**
* 将file类型的xml转换成对象
*/
public static Object convertXmlFileToObject(Class clazz, String xmlPath) {
Object xmlObject = null;
try {
JAXBContext context = JAXBContext.newInstance(clazz);
Unmarshaller unmarshaller = context.createUnmarshaller();
try (FileReader fr = new FileReader(xmlPath)) {
xmlObject = unmarshaller.unmarshal(fr);
}
} catch (Exception e) {
log.error("xml unmarshaller failed:{}", e);
}
return xmlObject;
}
}
注意的问题:
1. 请注意,解析结果为空的话,很可能是没有正确指定 namespace