O'Reilly logo

Java 9 Cookbook by Nick Samoylov, Mohamed Sanaulla

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

  1. Let's define the model object with the relevant properties and annotations that will be serialized into XML:
        @XmlRootElement
        @XmlAccessorType(XmlAccessType.FIELD) 
        class Messages{     
          @XmlElement 
          public final String message = "Hello World in XML"; 
        }

In the preceding code, @XmlRootElement is used to define the root tag, @XmlAccessorType is used to define the type of source for the tag name and tag values, and @XmlElement is used to identify the sources that become the tag name and tag values in the XML.

  1. Now, let's serialize an instance of the Message class into XML using JAXB:
 public class HelloWorldXml{ public static void main(String[] args) throws JAXBException{ JAXBContext jaxb = JAXBContext.newInstance(Messages.class); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required