javabean到XML的转换

javabeanXML的转换

一个javabeanXML的转换包,castor

当然这样的描述并不能完整的形容castor的功能;但在我下一步的应用中,我就是这么看待它的。

 上代码。

package castortest;

import java.io.*;

import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.mapping.MappingException;
import org.exolab.castor.xml.*;

public class FlightBeanMapTest {
	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 (if not already present)
			Mapping map = new Mapping();
			map.loadMapping("FlightBeanMapTestmapping.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 e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 

 

 

<!DOCTYPE databases PUBLIC
"-//EXOLAB/Castor Mapping DTD Version 1.0//EN"
"http://castor.exolab.org/mapping.dtd">

<mapping>
	<description>Basic mapping example</description>
	<class name="castortest.FlightBean" auto-complete="true">
		<map-to xml="flight"/>
		<field name="carrier">
			<bind-xml name="carrier" node="attribute"/>
		</field>
		<field name="departureTime">
			<bind-xml name="depart" node="attribute"/>
		</field>
		<field name="arrivalTime">
			<bind-xml name="arrive" node="attribute"/>
		</field>
	</class>
</mapping>

 

 

源码:

你可能感兴趣的:(xml,bean)