JAXBUtil.java
2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.huaheng.api.U8.tools;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
public class JAXBUtil {
private static final String ENCODING = "UTF-8";
private static final Log logger = LogFactory.getLog(JAXBUtil.class);
public static <T> T formXML(Class<T> clazz, String xml) {
JAXBContext jaxbContext = null;
T object = null;
if (xml != null && !"".equals(xml)) {
try {
jaxbContext = JAXBContext.newInstance(clazz);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(xml.getBytes(ENCODING));
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
JAXBElement<T> jaxbElement = unmarshaller.unmarshal(new StreamSource(byteArrayInputStream), clazz);
object = (T) jaxbElement.getValue();
} catch (Exception e) {
logger.error("error when unmarshalling from a xml string");
}
}
return object;
}
public static <T> String toXML(T object) {
String xml = "";
try {
JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass());
Marshaller marshaller = jaxbContext.createMarshaller();
// 是否格式化生成xml
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// 设置编码方式
marshaller.setProperty(Marshaller.JAXB_ENCODING, ENCODING);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
marshaller.marshal(object, byteArrayOutputStream);
byte[] buf = byteArrayOutputStream.toByteArray();
xml = new String(buf, 0, buf.length, ENCODING);
} catch (Exception e) {
e.printStackTrace();
logger.error("error when marshalling to a xml string");
}
return xml;
}
}