码迷,mamicode.com
首页 > 编程语言 > 详细

使用JAXB来实现Java合xml之间的转换

时间:2015-05-08 22:10:07      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:jaxb   javabean   xml   转换   

使用jaxb操作Java与xml之间的转换非常简单,看个例子就明白了。

    //javaBean-->xml
    @Test
    public void test1() {
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
            Marshaller marshaller = jaxbContext.createMarshaller();
            User user1 = new User("张三", "zhangsan", 123);
            marshaller.marshal(user1, System.out);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }

    //xml-->javaBean
    @Test
    public void test2() {
        try {
            String xml = "<user><money>123</money>"
                    + "<password>zhangsan</password><username>张三</username>"
                    + "</user>";
            JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
            Unmarshaller um = jaxbContext.createUnmarshaller();
            User user = (User) um.unmarshal(new StringReader(xml));
            System.out.println(user.getUsername() + "," + user.getMoney());
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }

使用JAXB来实现Java合xml之间的转换

标签:jaxb   javabean   xml   转换   

原文地址:http://blog.csdn.net/u012702547/article/details/45584087

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!