Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB marshalling Java to output XML file

problem is how do i generate XML file output instead of system.out?

package jaxbintroduction;

import java.io.FileOutputStream;
import java.io.OutputStream;

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        itemorder.Book quickXML = new itemorder.Book();

        quickXML.setAuthor("Sillyme");
        quickXML.setDescription("Dummie book");
        quickXML.setISBN(123456789);
        quickXML.setPrice((float)12.6);
        quickXML.setPublisher("Progress");
        quickXML.setTitle("Hello World JAVA");

        try {            
            javax.xml.bind.JAXBContext jaxbCtx = javax.xml.bind.JAXBContext.newInstance(quickXML.getClass().getPackage().getName());
            javax.xml.bind.Marshaller marshaller = jaxbCtx.createMarshaller();
            marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8"); //NOI18N
            marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.marshal(quickXML, System.out);
            OutputStream os = new FileOutputStream( "nosferatu.xml" );
            marshaller.marshal( quickXML, os );

        } catch (javax.xml.bind.JAXBException ex) {
            // XXXTODO Handle exception
            java.util.logging.Logger.getLogger("global").log(java.util.logging.Level.SEVERE, null, ex); //NOI18N
        }
    }

}
like image 292
Ket Avatar asked Dec 09 '12 15:12

Ket


People also ask

How does JAXB marshalling work?

In JAXB, marshalling involves parsing an XML content object tree and writing out an XML document that is an accurate representation of the original XML document, and is valid with respect the source schema. JAXB can marshal XML data to XML documents, SAX content handlers, and DOM nodes.

What is XML marshalling and Unmarshalling in Java?

Marshalling is the process of transforming Java objects into XML documents. Unmarshalling is the process of reading XML documents into Java objects. The JAXBContext class provides the client's entry point to the JAXB API.

What is XML marshalling?

Object/XML Mapping, or O/X mapping for short, is the act of converting an XML document to and from an object. This conversion process is also known as XML Marshalling, or XML Serialization. This chapter uses these terms interchangeably.

How does JAXB read XML?

To read XML, first get the JAXBContext . It is entry point to the JAXB API and provides methods to unmarshal, marshal and validate operations. Now get the Unmarshaller instance from JAXBContext . It's unmarshal() method unmarshal XML data from the specified XML and return the resulting content tree.


4 Answers

If you are using a JAXB 2.1 or greater then you can marshal directly to a java.io.File object:

 File file = new File( "nosferatu.xml" );
 marshaller.marshal( quickXML, file );

Corrsponding Javadoc

  • http://docs.oracle.com/javase/6/docs/api/javax/xml/bind/Marshaller.html#marshal%28java.lang.Object,%20java.io.File%29
like image 70
bdoughan Avatar answered Oct 19 '22 09:10

bdoughan


You are already marshalling to nosferatu.xml. Just remove or comment the line:

marshaller.marshal(quickXML, System.out);

if you don't wish to display the output and close the OutputStream:

os.close();
like image 24
Reimeus Avatar answered Oct 19 '22 10:10

Reimeus


Marshaller#marshall(...) method takes an OutputStream or Writer as parameter. Surely you would have found this in the API if you had looked.

like image 25
Hovercraft Full Of Eels Avatar answered Oct 19 '22 09:10

Hovercraft Full Of Eels


It is just an conversion process from java object to xml file. It is quite similar to serialization, you must be sure about serialization and marshalling. Here I have done the samples for marshalling. You can do unmarshalling in a similar way.

bean class with jaxp annotations:

package com.ofs.swinapps;

import javax.xml.bind.annotation.XmlRootElement;

    @XmlRootElement
    public class Employee {
    private String name;
    private String id;
    private String department;
    private int age;
    private int salary;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public int getAge() {
        return age;
}

    public void setAge(int age) {
        this.age = age;
    }

    public int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }
    }

marshalling:

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class Java2XMLExample {
    public static void main(String[] args) throws JAXBException {
 Employee employee = new Employee();
 employee.setName("Kowthal ganesh");
 employee.setAge(23);
 employee.setDepartment("Chola-ccms");
 employee.setId("947");
 employee.setSalary(8333);
 File file = new File("D:/build.xml");
 JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
 Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
 jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
 jaxbMarshaller.marshal(employee, file);
    }
}
like image 2
Kowthal ganesh kumar Avatar answered Oct 19 '22 09:10

Kowthal ganesh kumar