我正在尝试从 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>
您缺少 JAXB-Runtime 依赖项(因为您只定义了 JAXB-API 的依赖项,并且如您收到的错误消息所指出的那样)。
从JDK9开始,jaxb相关的类不再是JDK的一部分了
只需添加以下内容即可解决您的错误
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.9</version>
</dependency>