首页javajaxbJava HTML/XML - 如何从XML创建动态对象

Java HTML/XML - 如何从XML创建动态对象

我们想知道如何从XML创建动态对象。
import java.io.File;
import java.util.List;

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;

  }
}