簡體   English   中英

在Java 9中如何在沒有外部庫的情況下創建XML文件?

[英]How to create XML file without external libraries in Java 9?

在Java 9中如何在沒有外部庫的情況下創建XML文件?

當前,我正在使用javax.xml.bind.JAXBContextjavax.xml.bind.Marshaller類來執行此操作,但是在Java 9上這些類不再存在。 因此,在使用Java 9時,我遇到一個異常: java.lang.NoClassDefFoundError: javax/xml/bind/JAXBContext
我可以使用較低的Java版本創建XML文件,但我需要它與Java 9兼容。


我現在創建XML文件的方式是:

1.創建XML元素類

List<Athlete> athletes = new ArrayList<>();
Places places = new Places();
places.setAthletes(athletes);    
JAXBContext context = JAXBContext.newInstance(Places.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(places, new File(outputPath);
marshaller.marshal(places, System.out);

2.創建XML文件

 List<Athlete> athletes = new ArrayList<>(); Places places = new Places(); places.setAthletes(athletes); JAXBContext context = JAXBContext.newInstance(Places.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(places, new File(outputPath); marshaller.marshal(places, System.out); 


我希望有人已經遇到了這個問題,並且知道如何解決。

PS: 我已經搜索了該問題的答案,但未找到任何內容,因此它不應是重復的問題。
正如我提到的那樣, 我只需要使用Java內部庫即可。

您可以在Java 9中使用這些庫,但是需要包含它們的模塊。 確保您的module-info.javajava.xml模塊有要求:

module myModule {
    requires java.xml;
}

由於需要JAXB模塊提供更多功能,因此requiresmodule-info.java文件中添加更多module-info.java語句。 例如,完成module-info.java ,您的module-info.java文件可能看起來更像以下內容:

module myModule {
   java.xml
   java.xml.bind
   java.xml.ws
   java.xml.ws.annotation
}

有關更多信息,請參見如何解決Java 9中的java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM