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;
}
}
xml转换
最新推荐文章于 2024-08-24 22:01:16 发布