当前位置: 首页 > 工具软件 > Castor > 使用案例 >

Castor xsd生成java_利用Castor自动生成java文件

纪晨
2023-12-01

1、编写schema文件,例如:c:castorest.xsd。

2、到http://www.castor.org/网站下载castor-xml.jar(本文使用的是0.9.4版本)及编译所要引用的xerces-2.4.0.jar、xercesImpl.jar(http://www.apache.org/)文件。

3、执行以下脚本生成java文件:

java -classpath C:castorlibcastor-xml.jar;C:castorlibxerces-2.4.0.jar;C:castorlibxercesImpl.jar;. org.exolab.castor.builder.SourceGenerator -i test.xsd -package com.test.config.vo

4、生成的java文件中自动含包了unmarshal(通过XML文件生成java对象)和marshal(通过java对象生成xml文件)的两个方法。

5、marshal(通过java对象生成xml文件)方法代码如下:

public void marshal(java.io.Writer out)

throws org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException

{

Marshaller.marshal(this, out);

} //-- void marshal(java.io.Writer)

有时为了解决中文问题,我们需要自已实现该方法:

public void write2XML(String filename) throws IOException, MarshalException, ValidationException

{

//解决中文问题

FileOutputStream fos = new FileOutputStream(new File(filename));

OutputStreamWriter fw = new OutputStreamWriter(fos, "gb2312");

Marshaller ma = new Marshaller(fw);

ma.setEncoding("gb2312");

ma.marshal(wholeMsg);

}

6、unmarshal(通过XML文件生成java对象)方法代码如下:

public static com.test.config.vo.Test unmarshal(java.io.Reader reader)

throws org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException

{

return (com.test.config.vo.Test) Unmarshaller.unmarshal(com.test.config.vo.Test.class, reader);

} //-- com.test.config.vo.Test unmarshal(java.io.Reader)

由于生成的类可能比较多,我们可以采用一个统一的java类来控制他们:

private static Object createXMLObject(Class parserClass, Reader read)

{

Object obj = null;

try

{

Method method = parserClass.getMethod("unmarshal", new Class[]{Reader.class});

obj = method.invoke(parserClass, new Object[]{read});

}

catch (SecurityException e)

{

_log.error("在获取" + parserClass.getName() + "类的unmarshal方法时引发安全性异常!", e);

}

catch (NoSuchMethodException e)

{

_log.error("无法获取" + parserClass.getName() + "类的unmarshal方法!", e);

}

catch (IllegalArgumentException e)

{

_log.error("在调用" + parserClass.getName() + "类的unmarshal方法时出现异常!", e);

}

catch (IllegalAccessException e)

{

_log.error("在调用" + parserClass.getName() + "类的unmarshal方法时出现异常!", e);

}

catch (InvocationTargetException e)

{

_log.error("在调用" + parserClass.getName() + "类的unmarshal方法时出现异常!", e);

}

return obj;

}

 类似资料: