XML和实体类的转换

来源:互联网 发布:如何学java程序员 编辑:程序博客网 时间:2024/05/18 06:05
import java.io.StringReader;import java.io.StringWriter;import javax.xml.bind.JAXBContext;import javax.xml.bind.Marshaller;import javax.xml.bind.Unmarshaller;public class XmlUtils {/** * 将XML转为实体 * @param xml * @param c * @return */@SuppressWarnings("unchecked")public static <T>T jaxbxml2bean(String xml, Class<T> c) {  T t = null; try {              JAXBContext context = JAXBContext.newInstance(c);              Unmarshaller unmarshaller = context.createUnmarshaller();              t = (T) unmarshaller.unmarshal(new StringReader(xml));          } catch (Exception e) {              e.printStackTrace();          }return t;} /**      * JavaBean转换成xml      * @param obj      * @return       */      public static String bean2xml(Object obj) {          String result = null;          try {              JAXBContext context = JAXBContext.newInstance(obj.getClass());              Marshaller marshaller = context.createMarshaller();              marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);              marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");                StringWriter writer = new StringWriter();              marshaller.marshal(obj, writer);              result = writer.toString();          } catch (Exception e) {              e.printStackTrace();          }            return result;      } }

原创粉丝点击