xml解析工具

2025/10/28 Utils
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * XML 解析工具
 *
 * @author:saltedFish
 * @create:2022-11-07
 */
public class XmlParserUtil {

    /**
     * 使用JAXB解析XML文件并返回指定类型的对象。
     *
     * @param clazz       要解析的目标类
     * @param xmlFilePath XML文件的路径
     * @param <T>         目标类的泛型类型
     * @return 解析后的对象
     * @throws JAXBException 如果解析过程中发生错误
     * @throws IOException   如果文件未找到
     */
    public static <T> T unmarshal(Class<T> clazz, String xmlFilePath) throws JAXBException, IOException {
        try (FileInputStream fis = new FileInputStream(xmlFilePath)) {
            return unmarshal(clazz, fis);
        }
    }

    /**
     * 使用JAXB解析XML文件并返回指定类型的对象。
     *
     * @param clazz 要解析的目标类
     * @param file  文件对象
     * @param <T>   目标类的泛型类型
     * @return 解析后的对象
     * @throws JAXBException 如果解析过程中发生错误
     * @throws IOException   如果文件未找到
     */
    public static <T> T unmarshal(Class<T> clazz, File file) throws JAXBException, IOException {
        try (FileInputStream fis = new FileInputStream(file)) {
            return unmarshal(clazz, fis);
        }
    }

    /**
     * 使用JAXB解析XML输入流并返回指定类型的对象。
     *
     * @param clazz       要解析的目标类
     * @param inputStream XML输入流
     * @param <T>         目标类的泛型类型
     * @return 解析后的对象
     * @throws JAXBException 如果解析过程中发生错误
     */
    public static <T> T unmarshal(Class<T> clazz, InputStream inputStream) throws JAXBException {
        JAXBContext jaxbContext = createJAXBContext(clazz);
        Unmarshaller unmarshaller = createUnmarshaller(jaxbContext);
        return (T) unmarshaller.unmarshal(inputStream);
    }

    /**
     * 创建JAXBContext实例。
     *
     * @param clazz 要解析的目标类
     * @param <T>   目标类的泛型类型
     * @return JAXBContext实例
     * @throws JAXBException 如果创建过程中发生错误
     */
    private static <T> JAXBContext createJAXBContext(Class<T> clazz) throws JAXBException {
        return JAXBContext.newInstance(clazz);
    }

    /**
     * 创建Unmarshaller实例。
     *
     * @param jaxbContext JAXBContext实例
     * @return Unmarshaller实例
     * @throws JAXBException 如果创建过程中发生错误
     */
    private static Unmarshaller createUnmarshaller(JAXBContext jaxbContext) throws JAXBException {
        return jaxbContext.createUnmarshaller();
    }
}
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86