Writing an XML file marshalling an object

suggest change
import javax.xml.bind.annotation.XmlRootElement;

@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 java.io.File;
import javax.xml.bind.JAXB;

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

        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"?>
<user>
    <name>Jon Skeet</name>
    <userID>8884321</userID>
</user>

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents