JAXB XML Demo for Java SE

(Inspired by John Thompson's blog post Using JAXB for XML with Java)


One of the easiest ways to convert between Java objects and XML is with JAXB.  Originally, JAXB was only part of Java EE.  Over several years, Oracle included several Java EE APIs, including JAXB, in Java SE.  However, starting with Java 9 Oracle started to remove these APIs from SE.  But the jar files that implement them are available and can be run using Java SE.

To use JAXB with Java SE, you must configure both an implementation and the API, which is two separate jar files.  (A third jar is needed for this as well.)  With Maven, you merely specify the files you need and Maven locates them on the Internet, downloads them and any other jars they depend upon (if it hasn't already done that), and adds them to your CLASSPATH.  If not using Maven or some other dependency management tool, you will need to download the jar files required and make sure they are found on the CLASSPATH.  You can download these files using these links (check for and use newer versions if available):

javax.xml.bind  –  jaxb-api  (I used version 2.3.0 in this demo)

org.glassfish.jaxb  –  jaxb-runtime  (I used version in this demo)

javax.activation  –  javax.activation-api  (I used version 1.2.0 in this demo)

To run this demo, extract the folder JAXBdemo from JAXBdemo.zip.  (Or, save the individual files shown below, preserving the folder structure as shown.)  Then you can compile and run it using Maven:

C:\Temp>cd JAXBdemo
C:\Temp\JAXBemo>mvn install exec:java
...Maven INFO output omitted...
Generated "C:\Users\wpollock\Temp\JAXBdemo\product.xml".
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<product id="PO1">
    <description>HCC Coffee Mug</description>
...Maven INFO output omitted...

(This can be compiled and run using some IDE or just the javac and java command line tools, but using Maven is simpler.)

The link below shows the resulting product.XML file.

Top-Level Directory: JAXBdemo

Directory: src