Posts Tagged ‘jaxb’

Java to XML, XML to Java (Marshalling and Unmarshalling)

Wednesday, July 13th, 2011

Introduction

JDK6 and JAXB2.x (which comes with JDK6) make marshalling Java to XML and unmarshalling XML to Java a snap, almost trivial.

Example

Java to XML

package foo.bar;

import java.math.BigDecimal;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

public class JavaToXML {
	public static void main(String[] args) throws Exception {
		JAXBContext context = JAXBContext.newInstance(Product.class);

		Marshaller m = context.createMarshaller();
		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

		Product object = new Product();
		object.setCode("WI1");
		object.setName("Widget Number One");
		object.setPrice(BigDecimal.valueOf(300.00));

		m.marshal(object, System.out);
	}
}

XML to Java

package foo.bar;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class XMLToJava {

	public static void main(String[] args) {
		try {
			JAXBContext jc = JAXBContext.newInstance(Product.class);
			Unmarshaller u = jc.createUnmarshaller();

			File f = new File("product.xml");
			Product product = (Product) u.unmarshal(f);

			System.out.println(product.getCode());
			System.out.println(product.getName());
			System.out.println(product.getPrice());
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}
}

product.java

Note: the @XmlRootElement is vital here!

package foo.bar;

import java.math.BigDecimal;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Product {
	private String code;
	private String name;
	private BigDecimal price;

	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public BigDecimal getPrice() {
		return price;
	}
	public void setPrice(BigDecimal price) {
		this.price = price;
	}
}

product.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<product>
    <code>WI1</code>
    <name>Widget Number One</name>
    <price>300.0</price>
</product>

Tags: , ,
Posted in Examples | 7 Comments »

JAXB @XmlAnyElement example

Monday, June 7th, 2010

The problem

I was recently working on a JAXB centric app which was required to capture “arbitary” xml. e.g.

<a> 
   <b></b> 
   <c></c> 
   <d> 
       <!-- "Unknown" XML here --> 
       <maybee></maybee> 
       <maybef></maybef> 
       <!-- etc etc --> 
   <d></d> 
</d></a> 

How could I ever capture the contents of if they could be “anything”?
(more…)

Tags: , , ,
Posted in Development, quick tips | No Comments »