- Marshal Data Object to XML File


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



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)
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;

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");

	  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 as shown below.


\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">
    <Name>Frank Y. Ivy</Name>

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, 997👍, 0💬