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);