JAXB使用经验总结(一)

2014-11-24 02:57:39 · 作者: · 浏览: 3

使用JAXB首先要知道它是干什么的
当然,切入正题
很多时候我们需要把认知世界转化为我们熟悉的java对象,以供方便操作。这里,JAXB可以把xml对象转化为我们的java对象,也可以把java对象转化为xml对象。这时候我们就得知道它的两个转化方法。
一个是unmarshal(),一个是marshal()

unmarshal()是把xml对象转化为我们需要的java对象的方法,自然marshal()是把java对象转化为xml对象的一个过程。

我们需要的估计就是这两个方法的精华,只需要用到这么多就可以完成很多的事情了。下面看代码:


Java代码
private static T unmarshal(File templateFile, JAXBContext context) throws JAXBException {

final Unmarshaller unmarshaller = context.createUnmarshaller();

// Unmarshal the XML in the stringWriter back into an object
final T chart = (T) unmarshaller.unmarshal(templateFile);

return chart;
}

@SuppressWarnings("unchecked")
private static T unmarshal(String template, JAXBContext context) throws JAXBException {

final Unmarshaller unmarshaller = context.createUnmarshaller();

// Unmarshal the XML in the stringWriter back into an object
final T chart = (T) unmarshaller.unmarshal(new StringReader(template));

return chart;
}

这里templateFile 和 template 都是xml文件对象,这样的两个overload method就可以完成由xml对象转化为java对象了。

Java代码
private static String marshal(JAXBContext context, final T chart) throws JAXBException {
// Create the marshaller, this is the nifty little thing that will
// actually transform the object into XML
final Marshaller marshaller = context.createMarshaller();

// Create a stringWriter to hold the XML
final StringWriter stringWriter = new StringWriter();

// Marshal the javaObject and write the XML to the stringWriter
marshaller.marshal(chart, stringWriter);

String chartXml = stringWriter.toString();
return chartXml;
}


marshal()方法也贡献上。


方法都具备了 可以开工了。
Java代码
public static String process(File templateFile, Class type, ChartFiller filler) {
String chartXml = null;

try {
JAXBContext context = JAXBContext.newInstance(type);

final T chart = (T) unmarshal(templateFile, context);

filler.fill(chart);

chartXml = marshal(context, chart);

} catch (JAXBException e) {
log.error(e.getMessage(), e);
}
return chartXml;
}

public static String process(String template, Class type, ChartFiller filler) {
String chartXml = null;

try {
JAXBContext context = JAXBContext.newInstance(type);

final T chart = (T) unmarshal(template, context);

filler.fill(chart);

chartXml = marshal(context, chart);

} catch (JAXBException e) {
log.error(e.getMessage(), e);
}
return chartXml;
}

public interface ChartFiller {
void fill(T chart);
}


工具方法都上齐了,你就可以在你需要的地方调用了。当然,我还没讲我们的java操作对象。

下面举个例子,比如上面出现的chart 就是我们需要操纵的对象,它可能是一个xml对象,而我们需要操作的是java对象,晕了吧:
比如我们的chart是在页面需要显示的图形,比如fusioncharts 的某个图,先定义为chart,它会是一个接口类,是所有xxxChart的父类。 比如我的具体chart名叫GaugeChart。

代码如下,别说晕说郁闷了:

Java代码
public interface Chart {

}

Java代码
@XmlRootElement(name = "chart")
public class GaugeChart implements Chart {

@XmlAttribute
private String lowerLimit;

@XmlAttribute
private String upperLimit;

@XmlAttribute
private String lowerLimitDisplay;

@XmlAttribute
private String upperLimitDisplay;

@XmlAttribute