简体   繁体   中英

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

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

Currently I am using javax.xml.bind.JAXBContext and javax.xml.bind.Marshaller classes to do that, but on Java 9 these classes does not exist any more. So while using Java 9 I am getting an exception: java.lang.NoClassDefFoundError: javax/xml/bind/JAXBContext .
I can create XML file with lower Java version, but I need it will be compatible and for Java 9.


The way I am creating XML file right now is:

1. Create XML element class

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. Create XML file

 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); 


I hope someone encountered with this problem already and know how to solve it.

PS: I have searched for the answer of this question but doesn't found anything, so it shouldn't be a duplicated question.
As I mention I have to use only Java internal libraries for that.

You can use these libraries in Java 9, but you need to require the module that contains them. Ensure that your module-info.java has a requirement for the java.xml module:

module myModule {
    requires java.xml;
}

As you require more functionality from the JAXB modules, you will need to add more requires statements in your module-info.java file. For example, your module-info.java file may look more like the following when you are done:

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

For more information, see How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException in Java 9 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM