JAXB (JSR-222)@XmlID
实现可以使用和的组合轻松处理文档中的引用@XmlIDREF
。我将在下面用一个例子来演示。
JAVA模型
图形
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
类中你需要使用@XmlID
注解来表明该id
字段是id。
package forum13404583;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
class Vertex {
@XmlAttribute
@XmlID
String id;
@XmlAttribute
String color;
@XmlAttribute
Integer thickness;
}
边缘
在Edge
类中,@XmlIDREF
注释用于指示 XML 值包含引用实际值的外键。
package forum13404583;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
class Edge {
@XmlAttribute
@XmlIDREF
Vertex end1;
@XmlAttribute
@XmlIDREF
Vertex end2;
}
演示代码
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);
}
}
输入(输入.xml)/输出
下面是运行演示代码的输入和输出。
<?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>
了解更多信息