【问题标题】:Dynamic java from XML来自 XML 的动态 java
【发布时间】:2012-11-15 19:19:39
【问题描述】:

我想为我的域对象构建某种对象生成引擎。 例如,假设我正在使用图表。模型由 xml 表示,我应该能够在运行时加载它们并构建 java 表示。

可以说,图有顶点和边 所以它看起来像这样:

<graph>
   <vertex id="n1" color="red", thickness="2">
   <vertex id="n2">
   <edge end1="${n1}", end2="${n2}"/>
</graph>

为此,我想获取可以由以下 java 类描述的对象:

class Graph {
     List<Vertex> vertexList
     List<Edge> edgeList
}

class Vertex {
   String id
    ... various properties ... 
}

class Edge {
   Vertex end1
   Vertex end2
}

另一个要求是能够像这样在循环中定义顶点:

<graph>
  ...
    <for var = i, min = 1, max = 10, step = 1>
      <vertex id=$i.../> 
    </for>
  ... 
</graph>

我考虑过使用 Apache Jelly,但它似乎是一个“死”项目,JaxB 不允许这种级别的动态行为 AFAIK...

我的问题是 - 你可以推荐什么框架来实现这样的任务?

如果有一些像 Apache Jelly 一样工作但仍被维护的东西,它也可能很棒:)

提前非常感谢

【问题讨论】:

  • 为什么需要为循环生成“xml”?
  • 例如,我想到了 JSTL。真正的任务是提供一种方便的方法来生成一组资源(例如,我想生成一个包含 1000 个顶点的图用于测试目的)。所以我想以声明的方式定义一个图。
  • 这里没有真正的问题。您的需求可以解释为以 XML 编码的 DSL(领域特定语言)。您可以充实 DSL(for 循环可能是其中的一部分),然后编写一些 Java 代码来适当地读取和解释 XML。使用 SAXParser 会很简单。

标签: java xml jaxb jelly


【解决方案1】:

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);
    }

}

输入 (input.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>

更多信息

【讨论】:

  • 非常感谢,布莱斯!我完全错过了 JaXB 的这个功能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-27
  • 2012-12-18
  • 2011-06-06
  • 1970-01-01
  • 2015-08-08
  • 1970-01-01
相关资源
最近更新 更多