cuikaidong
2025-06-12 44e283b774bb1168d0c17dfe5070a1ca8e2274cd
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
package org.jeecg.modules.iot.util;
 
import lombok.extern.slf4j.Slf4j;
 
import javax.xml.bind.*;
import java.io.*;
 
/**
 * JAXB工具类
 *
 * @author cuikaidong
 * 2024年12月20日
 */
@Slf4j
public class JaxbUtil {
    private static JAXBContext jaxbContext;
 
    //xml转java对象
    public static Object xmlToBean(String str, Class<?> load) {
        Object object = null;
        try {
            File file = new File(str);
            JAXBContext jaxbContext = JAXBContext.newInstance(load);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            object = unmarshaller.unmarshal(file);
        } catch (JAXBException e) {
            log.error("xml转换到实体时出错,xml信息={},报错信息={}!", str, e);
        }
        return object;
    }
 
    //java对象转xml
    public static String beanToXml(Object obj) {
        StringWriter writer = null;
        try {
            jaxbContext = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = jaxbContext.createMarshaller();
            //Marshaller.JAXB_FRAGMENT:是否省略xml头信息,true省略,false不省略
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
            //Marshaller.JAXB_FORMATTED_OUTPUT:决定是否在转换成xml时同时进行格式化(即按标签自动换行,否则即是一行的xml)
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            //Marshaller.JAXB_ENCODING:xml的编码方式
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            writer = new StringWriter();
            marshaller.marshal(obj, writer);
        } catch (JAXBException e) {
            log.info(e.getMessage());
        }
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + writer.toString();
    }
}