JAXB (JSR-222) implementations can easily handle references within a document using a combination of @XmlID
and @XmlIDREF
. I will demonstrate below with an example.
JAVA MODEL
Graph
package forum13404583;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
class Graph {
@XmlElement(name = "vertex")
List<Vertex> vertexList;
@XmlElement(name = "edge")
List<Edge> edgeList;
}
Vertex
In the Vertex
class you need to use the @XmlID
annotation to indicate that the id
field is the id.
package forum13404583;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
class Vertex {
@XmlAttribute
@XmlID
String id;
@XmlAttribute
String color;
@XmlAttribute
Integer thickness;
}
Edge
In the Edge
class the @XmlIDREF
annotation is used to indicate that the XML value contains a foreign key that references the real value.
package forum13404583;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
class Edge {
@XmlAttribute
@XmlIDREF
Vertex end1;
@XmlAttribute
@XmlIDREF
Vertex end2;
}
DEMO CODE
package forum13404583;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Graph.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum13404583/input.xml");
Graph graph = (Graph) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(graph, System.out);
}
}
INPUT (input.xml)/OUTPUT
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>
For More Information