Java HTML / XML How to - Create Dynamic object from XML








Question

We would like to know how to create Dynamic object from XML.

Answer

import java.io.File;
import java.util.List;
//from w  ww .ja v a  2s.  c  o  m
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlIDREF;
import javax.xml.bind.annotation.XmlRootElement;

public class Main {

  public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Graph.class);

    Unmarshaller unmarshaller = jc.createUnmarshaller();
    File xml = new File("input.xml");
    Graph graph = (Graph) unmarshaller.unmarshal(xml);

    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(graph, System.out);
  }

  @XmlRootElement
  @XmlAccessorType(XmlAccessType.FIELD)
  public static class Graph {

    @XmlElement(name = "vertex")
    List<Vertex> vertexList;

    @XmlElement(name = "edge")
    List<Edge> edgeList;

  }

  @XmlAccessorType(XmlAccessType.FIELD)
  public static class Edge {

    @XmlAttribute
    @XmlIDREF
    Vertex end1;

    @XmlAttribute
    @XmlIDREF
    Vertex end2;

  }

  @XmlAccessorType(XmlAccessType.FIELD)
  public static class Vertex {

    @XmlAttribute
    @XmlID
    String id;

    @XmlAttribute
    String color;

    @XmlAttribute
    Integer thickness;

  }
}

Below is the input to and output from running the demo code.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<graph>
    <vertex id="n1" color="red" thickness="2"/>
    <vertex id="n2"/>
    <edge end1="n1" end2="n2"/>
</graph>