从 java 对象创建 XML

问题描述 投票:0回答:1

我正在尝试从 Java 对象创建 XML,但收到错误“在模块路径或类路径上未找到 JAXB-API 的实现”。请帮我解决错误。

@RequestMapping(value = "/writeToFile",method = RequestMethod.POST)
    public String writeFileXML(@RequestBody Customer customer) {
        try {
            File file=new File("D:\\vendorfile\\customer.xml");
            FileWriter fileWriter=new FileWriter(file);
            JAXBContext jaxbContext=JAXBContext.newInstance(Customer.class);
            Marshaller marshaller=jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.marshal(customer, fileWriter);
            return "Marshaller successfull";
        }catch(IOException ioException) {
            return ioException.getMessage();
        }catch(Exception ex) {
            return ex.getMessage();
        }
    }
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.0</version>
        </dependency>
java spring spring-boot jaxb
1个回答
0
投票

您缺少 JAXB-Runtime 依赖项(因为您只定义了 JAXB-API 的依赖项,并且如您收到的错误消息所指出的那样)。

从JDK9开始,jaxb相关的类不再是JDK的一部分了

只需添加以下内容即可解决您的错误

<dependency>
    <groupId>org.glassfish.jaxb</groupId>
    <artifactId>jaxb-runtime</artifactId>
    <version>2.3.9</version>
</dependency>
© www.soinside.com 2019 - 2024. All rights reserved.