MyUserToXml.java - Marshal Data Object to XML File

Q

How to marshal data objects to XML files using JAXB API?

✍: FYIcenter.com

A

If you want to marshal data objects to XML files using JAXB API, you can follow these suggestions:

1. Create a JAXBContext instance with the package name of the data type classes generated with the JAXB XJC tool:

      JAXBContext c = JAXBContext.newInstance("com.fyicenter.demo");	  

2. Then create a Marshaller instance from the JAXBContext:

      Marshaller m = c.createMarshaller();

3. Finally, marshal the data object with the Marshaller to an XML file. You can set JAXB_FORMATTED_OUTPUT property to true, if you want the output XML file to nicely formatted with line breaks.

	  m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
      m.marshal(u,new FileOutputStream("UserOutput.xml"));

Here is the entire example program,

// Copyright (c) FYIcenter.com
import com.fyicenter.demo.User;
import com.fyicenter.demo.ObjectFactory;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import java.io.*;

public class MyUserToXml {
   public static void main(String[] args) throws Exception {
      XMLGregorianCalendar d = DatatypeFactory.newInstance()
         .newXMLGregorianCalendarDate(1970, 1, 1, 1);

	  System.out.println("Create user object...");
      ObjectFactory f = new ObjectFactory();
      User u = f.createUser();
      u.setName("Frank Y. Ivy");
	  u.setBirthDate(d);
	  u.setSex("Male");
      u.setID(101);

	  System.out.println("Marshal user object to XML file...");
      JAXBContext c = JAXBContext.newInstance("com.fyicenter.demo");	  
      Marshaller m = c.createMarshaller();
      m.marshal(u,new FileOutputStream("UserOutput.xml"));
    }
}

Compile and run MyUserToXml.java as shown below.

\fyicenter\src>\local\jdk-1.8.0\bin\javac MyUserToXml.java

\fyicenter\src>\local\jdk-1.8.0\bin\java MyUserToXml
Create user objec...
Marshal user objec to XML file...

\fyicenter\src>type UserOutput.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<User ID="101">
    <BirthDate>1970-01-01+00:01</BirthDate>
    <Name>Frank Y. Ivy</Name>
    <Sex>Male</Sex>
</User>

The output XML file looks good. It should match the XML schema defined in User.xsd.

 

Examples for JAXB (Java Architecture for XML Binding)

⇒⇒FAQ for jaxb-*.jar - Java Architecture for XML Binding

2017-06-30, 460👍, 0💬