jaxb实现javabean和xml间互相转换
  yXrgnj2AQg6w 2023年11月02日 43 0

1.java bean->xml

@Test    public void marshalTest() {        try {            JAXBContext jContext = JAXBContext.newInstance(User.class);            Marshaller marshaller = jContext.createMarshaller();            Pet pet = new Pet("dog","小哈");            Book aBook = new Book("平凡的世界", 20);            Book bBook = new Book("明晓溪",15);            List<Book> books = new ArrayList<Book>();            books.add(aBook);            books.add(bBook);            User user = new User("张三","女", 20, new Date(), null, pet, books);            //设置生成的xml的编码            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");            //设置生成的xml内容是否format,否的话是显示一行            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);            //是否省略头部声明信息,默认false            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);            //直接输出文件            marshaller.marshal(user, new File("a.xml"));                        OutputStream out = new ByteArrayOutputStream();            //输出字节流            marshaller.marshal(user, out);            System.out.println("========"+out.toString());        } catch (JAXBException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }

JDK1.7及之后做了更多封装,更加简单: 

JAXB.marshal(user, new File("b.xml"));

2.xml->javabean

@Test    public void unmarshallTest() {        try {            JAXBContext jaxbContext = JAXBContext.newInstance(User.class);            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();            User user = (User) unmarshaller.unmarshal(new File("a.xml"));            System.out.println(user.toString());                    } catch (JAXBException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }

1.7及之后:

User user2 = JAXB.unmarshal(new File("b.xml"), User.class);

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  2Vtxr3XfwhHq   2024年05月17日   53   0   0 Java
  Tnh5bgG19sRf   2024年05月20日   107   0   0 Java
  8s1LUHPryisj   2024年05月17日   46   0   0 Java
  aRSRdgycpgWt   2024年05月17日   47   0   0 Java
yXrgnj2AQg6w