betwixt로 Javabean与XML 사이전환

필요한 jar package(http://commons.apache.org)

betwixt API 참고:http://commons.apache.org/betwixt/betwixt-0.8/docs/apidocs/index.html

commons-beanutils-1.8.3.jar
commons-betwixt-0.8.jar
commons-collections-3.2.1.jar
commons-digester-2.1.jar
commons-logging-1.1.1.jar

 

package test;

import java.beans.IntrospectionException;

import java.io.IOException;

import java.io.PrintWriter;

import java.io.StringWriter;

import org.apache.commons.betwixt.io.BeanWriter;

import org.xml.sax.SAXException;



public class Bean2Xml{

    public static void main(String[] args) {

        StringWriter outputWriter = new StringWriter();  

        outputWriter.write("<?xml version='1.0' ?>/n");

        BeanWriter writer = new BeanWriter(outputWriter);

        writer.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);

        writer.getBindingConfiguration().setMapIDs(false);

        writer.enablePrettyPrint();

        try {

            writer.write("personbean", new Person("Kimura",20));  //abstractBeanWriter의 write(String qualifiedName,Object bean)

            PrintWriter pw = new PrintWriter("personbean.xml"); 

            pw.write(outputWriter.toString());

            outputWriter.close();

            pw.close();

        } catch (IOException e) {

            e.printStackTrace();

        } catch (SAXException e) {

            e.printStackTrace();

        } catch (IntrospectionException e) {

            e.printStackTrace();

        }

    }

}

 

//xml을 bean으로
BeanReader beanReader
= new BeanReader(); beanReader.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false); beanReader.getBindingConfiguration().setMapIDs(false); beanReader.registerBeanClass("person", Person.class); PersonBean person = (PersonBean) beanReader.parse(xmlReader); System.out.println(person);

 

 

你可能感兴趣的:(javabean)