Castor -- 将Java对象和XML自动绑定的程序
2008-01-05 19:22:17 来源:WEB开发网核心提示:1. Castor是什么Castor是一种将java对象和xml自动绑定的开源软件. 它可以在Java对象,XML文本,SQL数据表以及LDAP目录之间绑定.²网址: http://www.castor.org/2. Castor使用²Java对象指的是具有setX和getX方法的JavaBean,
1. Castor是什么
Castor是一种将java对象和xml自动绑定的开源软件. 它可以在Java对象,XML文本,SQL数据表以及LDAP目录之间绑定.
²网址: http://www.castor.org/
2. Castor使用
²Java对象指的是具有setX和getX方法的JavaBean,将Castor用于JavaBean具体使用方法如下:
Ø缺省用法: 缺省用法指的是没有使用映射格式描述文件时的用法
import java.io.*;
import org.exolab.castor.xml.*;
public class Test
{
public static void main(String[] argv) {
// build a test bean
FlightBean bean = new FlightBean();
bean.setCarrier("AR");
bean.setNumber(426);
bean.setDepartureTime("6:23a");
bean.setArrivalTime("8:42a");
try {
// write it out as XML
File file = new File("test.xml");
Writer writer = new FileWriter(file);
Marshaller.marshal(bean, writer);
// now restore the value and list what we get
Reader reader = new FileReader(file);
FlightBean read = (FlightBean)
Unmarshaller.unmarshal(FlightBean.class, reader);
System.out.PRintln("Flight " + read.getCarrier() +
read.getNumber() + " departing at " +
read.getDepartureTime() +
" and arriving at " + read.getArrivalTime());
} catch (IOException ex) {
ex.printStackTrace(System.err);
} catch (MarshalException ex) {
ex.printStackTrace(System.err);
} catch (ValidationException ex) {
ex.printStackTrace(System.err);
}
}
}
Ø 标准用法:
import java.io.*;
import org.exolab.castor.xml.*;
import org.exolab.castor.mapping.*;
public class Test
{
public static void main(String[] argv) {
// build a test bean
FlightBean bean = new FlightBean();
bean.setCarrier("AR");
bean.setNumber(426);
bean.setDepartureTime("6:23a");
bean.setArrivalTime("8:42a");
try {
// write it out as XML
Mapping map=new Mapping();
map.loadMapping("mapping.xml");
File file = new File("test.xml");
Writer writer = new FileWriter(file);
Marshaller marshaller =new Marshaller(writer);
marshaller.setMapping(map);
marshaller.marshal(bean);
// now restore the value and list what we get
Reader reader = new FileReader(file);
Unmarshaller unmarshaller = new Unmarshaller(map);
FlightBean read = (FlightBean)unmarshaller.unmarshal(reader);
System.out.println("Flight " + read.getCarrier() +
read.getNumber() + " departing at " +
read.getDepartureTime() +" and arriving at " + read.getArrivalTime());
} catch (IOException ex) {
ex.printStackTrace(System.err);
} catch (MarshalException ex) {
ex.printStackTrace(System.err);
} catch (ValidationException ex) {
ex.printStackTrace(System.err);
}
catch (MappingException ex) {
ex.printStackTrace(System.err);
}
}
}
Ø :缺省用法生成的XML文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<arrival-time>8:42a</arrival-time>
<departure-time>6:23</departure-time>
<carrier>AR</carrier>
也就是说
•对于具有基本类型值的属性创建元素的一个属性(本例中只有 number 属性通过 getNumber() 方法公开为 int 值)。
更多精彩
赞助商链接