以使用它把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 { ...... }