Jaxb2.0实现Java Object转换Xml转换Java Object.(一)

2014-11-24 08:54:15 · 作者: · 浏览: 3
[java]
//测试类
[java]
import com.toft.webservice.client.domino.DominoObject; 
 
import com.toft.webservice.core.JaxbBinder;


public class JaxbTest {

private static final String DECLARATION = "< xml version='1.0' encoding='utf-8' >";
private static final String ENCODING = "UTF-8";
private DominoObject dominoObject = new DominoObject();
public static void main(String[] args){

}

/**
* 使用JAXB生成符合接口的XML.
* @return String
* @throws Exception
*/
private String getDominoXml() throws Exception {
try {
JaxbBinder binder = new JaxbBinder(DominoObject.class);
return binder.toXml(dominoObject, ENCODING, DECLARATION);
} catch (Exception e) {
throw e;
}
}
}


 
 
 
//工具类
import java.io.StringReader; 
 
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
* 使用Jaxb2.0实现XML<->Java Object的Binder.
*
* @author 孙祖强
*/
public class JaxbBinder {
//多线程安全的Context.
private JAXBContext jaxbContext;

/**
* @param types 所有需要序列化的Root对象的类型.
*/
public JaxbBinder(Class< >... types) {
try {
jaxbContext = JAXBContext.newInstance(types);
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}

/**
* Java Object->Xml.
*/
public String toXml(Object root) {
try {
StringWriter writer = new StringWriter();
createMarshaller("UTF-8", null, true).marshal(root, writer);
return writer.toString();
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}

/**
* Java Object->Xml.
*/
public String toXml(Object root, String encoding) {
try {
StringWriter writer = new StringWriter();
createMarshaller(encoding, null, false).marshal(root, writer);
return writer.toString();
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}

/**
* Java Object->Xml.
*/
public String toXml(Object root, String encoding, String declaration) {
try {
StringWriter writer = new StringWriter();
writer.append(declaration);
createMarshaller(encoding, declaration, false).marshal(root, writer);
return writer.toString();
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}

/**
* Xml->Java Object.
*/
@SuppressWarnings("unchecked")
public T fromXml(String xml) {
try {
StringReader reader = new StringReader(xml);
return (T) createUnmarshaller().unmarshal(reader);
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}

/**
* 创建Marshaller, 设定encoding(可为Null), 设定declaration(可为Null).
*/
public Marshaller createMarshaller(String encoding, String declaration, Boolean formatted) {
try {
Marshaller marshaller = jaxbContext.createMarshaller();

//是否格式化XML