JAVA : JAXB Basics

import java.io.FileReader;
import java.io.FileWriter;
import java.io.Writer;

import javax.swing.text.StyledEditorKit.BoldAction;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name = "dog")
@XmlType(propOrder = { "name", "owner" })
public class Dog {

	private String name;
	private String owner;

	@XmlElement(name = "dogoName")
	public String getName() {
		return name;
	}

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

	public String getOwner() {
		return owner;
	}

	public void setOwner(String owner) {
		this.owner = owner;
	}

	public static void main(String[] args) {
		Dog dog = new Dog();
		dog.setName("pinky");
		dog.setOwner("sam");
		Writer wrt = null;
		try {
			JAXBContext cntx = JAXBContext.newInstance(Dog.class);
			Marshaller mrsh = cntx.createMarshaller();
			mrsh.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
			wrt = new FileWriter("./doggy.xml");
			// mrsh.marshal(dog, System.out);
			mrsh.marshal(dog, wrt);
			Unmarshaller umrsh = cntx.createUnmarshaller();
			Dog doggy = (Dog) umrsh.unmarshal(new FileReader("./doggy.xml"));
			System.out.println("name: " + doggy.getName());
			
		} catch (Exception e) {
		} finally {
			if (wrt != null) {
				try {
					wrt.close();
				} catch (Exception e) {
				}
			}
		}

	}

}

And if you want to disable xml declaration

mrsh.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

Original Reference
vogella
and
stackoverflow

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: