Java HTML / XML How to - Unmarshal XML using JAXB








Question

We would like to know how to unmarshal XML using JAXB.

Answer

import java.io.File;
import java.util.List;
//from ww w . j a v  a  2  s  .  co m
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;

public class Main {
  public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Items.class);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    File xml = new File("input.xml");
    Items items = (Items) unmarshaller.unmarshal(xml);
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(items, System.out);
  }
  @XmlRootElement
  public static class Items {
    List<Item> items;
    @XmlElement(name = "item")
    public List<Item> getItems() {
      return items;
    }
    public void setItems(List<Item> items) {
      this.items = items;
    }
  }
  public static class Item {
    int code;
    String name;
    int price;
    public int getCode() {
      return code;
    }
    public void setCode(int code) {
      this.code = code;
    }

    public String getName() {
      return name;
    }

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

    public int getPrice() {
      return price;
    }

    public void setPrice(int price) {
      this.price = price;
    }
  }
}

input.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<items>//  w w w .java  2  s  . c  o  m
    <item>
        <code>12000</code>
        <name>Samsung  620</name>
        <price>9999</price>
    </item>
    <item>
        <code>15000</code>
        <name>NOKIA</name>
        <price>19999</price>
    </item>
    <item>
        <code>18000</code>
        <name>HTC 620</name>
        <price>29999</price>
    </item>
</items>