您的位置:首页 > 编程语言 > Java开发

xml与java实体相互转化

2016-08-17 16:56 267 查看
1、实体转换类:

public abstract class BuildXmlUtils<T> {

    /**

     * 获得泛型实体

     * @return

     * @throws InstantiationException

     * @throws IllegalAccessException

     */

    @SuppressWarnings("unchecked")

    public T getT() throws InstantiationException, IllegalAccessException {

        Type sType = getClass().getGenericSuperclass();

        Type[] generics = ((ParameterizedType) sType).getActualTypeArguments();

        Class<T> mTClass = (Class<T>) (generics[0]);

        return mTClass.newInstance();

    }

    /**

     * 实体bean转成xml

     * @param message 实体bean

     * @return String

     */

    public String bean2xml(T message) {

        String result = null;

        JAXBContext context = null;

        Marshaller marshaller = null;

        String __defult_encoding = "UTF-8";

        try {

            context = JAXBContext.newInstance(message.getClass());

            marshaller = context.createMarshaller();

            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            marshaller.setProperty(Marshaller.JAXB_ENCODING, __defult_encoding);

            StringWriter writer = new StringWriter();

            marshaller.marshal(message, writer);

            result = writer.toString();

        } catch (Exception e) {

            e.printStackTrace();

        }

        return result;

    }

    /**

     * xml转实体bean

     * @param xmlStr xml字符窜

     * @return

     */

    @SuppressWarnings("unchecked")

    public T xml2bean(String xmlStr) {

        T message = null;

        Reader reader = null;

        JAXBContext context = null;

        Unmarshaller unmarshaller = null;

        try {

            reader = new StringReader(xmlStr);

            context = JAXBContext.newInstance(getT().getClass());

            unmarshaller = context.createUnmarshaller();

            message = (T) unmarshaller.unmarshal(reader);

            reader.close();

        } catch (JAXBException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        } catch (InstantiationException e) {

            e.printStackTrace();

        } catch (IllegalAccessException e) {

            e.printStackTrace();

        } finally {

            try {

                if (reader != null)

                    reader.close();

            } catch (IOException e) {

                reader = null;

                e.printStackTrace();

            }

        }

        return message;

    }

}
2、在实体需要使用@XmlAccessorType、@XmlType、@XmlRootElement等xml标签进行注解
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java xml