Java Language JAXB Writing an XML file (marshalling an object)


import javax.xml.bind.annotation.XmlRootElement;

public class User {

    private long userID;
    private String name;
    // getters and setters

By using the annotation XMLRootElement, we can mark a class as a root element of an XML file.

import javax.xml.bind.JAXB;

public class XMLCreator {
    public static void main(String[] args) {
        User user = new User();
        user.setName("Jon Skeet");

        try {
            JAXB.marshal(user, new File("UserDetails.xml"));
        } catch (Exception e) {
            System.err.println("Exception occurred while writing in XML!");
        } finally {
            System.out.println("XML created");

marshal() is used to write the object's content into an XML file. Here userobject and a new File object are passed as arguments to the marshal().

On successful execution, this creates an XML file named UserDetails.xml in the class-path with the below content.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <name>Jon Skeet</name>