Castor -- 将Java对象和XML自动绑定的程序

王朝java/jsp·作者佚名  2008-05-31
宽屏版  字体: |||超大  

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-time8:42a</arrival-time

<departure-time6:23</departure-time

<carrierAR</carrier

也就是说

•对于具有基本类型值的属性创建元素的一个属性(本例中只有 number 属性通过 getNumber() 方法公开为 int 值)。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有