JaxbTest.java 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package com.primeton.dgs.workspace.extractor.jaxb;
  2. import org.junit.Test;
  3. import javax.xml.bind.JAXBContext;
  4. import javax.xml.bind.JAXBException;
  5. import javax.xml.bind.Marshaller;
  6. import javax.xml.bind.Unmarshaller;
  7. import java.io.File;
  8. /**
  9. * <pre>
  10. *
  11. * Created by zhaopx.
  12. * User: zhaopx
  13. * Date: 2019/9/10
  14. * Time: 14:10
  15. *
  16. * </pre>
  17. *
  18. * @author zhaopx
  19. */
  20. public class JaxbTest {
  21. @Test
  22. public void saveXmlTest() {
  23. User user = new User("陈本布衣", 2018, "超级管理员","瞎哔哔");
  24. File file = new File("user.xml");
  25. try {
  26. JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
  27. Marshaller marshaller = jaxbContext.createMarshaller();
  28. //格式化输出,即按标签自动换行,否则就是一行输出
  29. marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  30. //设置编码(默认编码就是utf-8)
  31. marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
  32. //是否省略xml头信息,默认不省略(false)
  33. marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);
  34. marshaller.marshal(user, file);
  35. } catch (JAXBException e) {
  36. e.printStackTrace();
  37. }
  38. }
  39. @Test
  40. public void getUserTest() {
  41. File file = new File("user.xml");
  42. try {
  43. JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
  44. Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
  45. User user = (User) unmarshaller.unmarshal(file);
  46. System.out.println(user.toString());
  47. } catch (JAXBException e) {
  48. e.printStackTrace();
  49. }
  50. }
  51. }