2

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

@XmlRootElement
public class Places {

    private List<Athlete> athletes;

    public List<Athlete> getAthletes() {
        return athletes;
    }

    @XmlElement
    public void setAthletes(List<Athlete> athletes) {
        this.athletes = athletes;
    }
}  

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.

P.S.: 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.

Dumbo
  • 1,630
  • 18
  • 33

1 Answers1

3

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.

Justin Albano
  • 3,809
  • 2
  • 24
  • 51