Jakarta-Common-BetWixt使用笔记
时间:2011-01-28 csdn博客 沈斌
以使用它把Javabean转换成XML并输出。
下载地址:http://commons.apache.org/beanutils/
代码如下:
Javabean:
package demo.bean;
public class Music ...{
private String name;
private String mp3File;
public String getName() ...{
return name;
}
public void setName(String name) ...{
this.name = name;
}
public String getMp3File() ...{
return mp3File;
}
public void setMp3File(String mp3File) ...{
this.mp3File = mp3File;
}
}
测试代码:
package demo;
import java.beans.IntrospectionException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import org.apache.commons.betwixt.io.BeanWriter;
import org.xml.sax.SAXException;
import demo.bean.Music;
public class BetwixtDemo ...{
public static void main(String[] args) throws IOException, SAXException, IntrospectionException ...{
Music music = new Music();
music.setName("music_name");
music.setMp3File("music_mp3file");
Writer outputWriter = new FileWriter("e:\test.xml");
BeanWriter beanWriter = new BeanWriter(outputWriter);
beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
beanWriter.getBindingConfiguration().setMapIDs(false);
beanWriter.enablePrettyPrint();
beanWriter.setEndTagForEmptyElement(true);
beanWriter.setIndent(" ");
beanWriter.writeXmlDeclaration("<?xml version="1.0" encoding="UTF-8" ?>");
beanWriter.write("Msg", music);
outputWriter.close();
}
}
可指定NameMapper来重新定义大小写
beanWriter.getXMLIntrospector().getConfiguration().setElementNameMapper(new org.apache.commons.betwixt.strategy.DecapitalizeNameMapper());
其中:
DecapitalizeNameMapper 指定义小写
CapitalizeNameMapper 指定为大写
HyphenatedNameMapper 指定为连接符 比如mp3File ==> mp3-file
可以通过HyphenatedNameMapper.setUpperCase(true)设置首字母的大小写
也可实现NameMapper来定义自己的现实方式
如:class ItsANameMapper implements NameMapper { ...... } |