Tuesday, December 29, 2015

JAXB: Marshalling kickstart blank template application

This is a simple JAXB application, that could be used as template. It has console (and file) output.

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAttribute;

@XmlRootElement
public class Test {
    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

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

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }



    public static void main(String[] args) {

        Test test = new Test();
        test.setId(100);
        test.setName("Tim Rott");
        test.setAge(29);

        try {

//            File file = new File("C:\\file.xml");
            JAXBContext jaxbContext = JAXBContext.newInstance(Test.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

            // output pretty printed
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

//            jaxbMarshaller.marshal(test, file);
            jaxbMarshaller.marshal(test, System.out);

        } catch (JAXBException e) {
            e.printStackTrace();
        }

    }
}

No comments:

Post a Comment