12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- package com.primeton.dgs.workspace.extractor.jaxb;
- import org.junit.Test;
- import javax.xml.bind.JAXBContext;
- import javax.xml.bind.JAXBException;
- import javax.xml.bind.Marshaller;
- import javax.xml.bind.Unmarshaller;
- import java.io.File;
- /**
- * <pre>
- *
- * Created by zhaopx.
- * User: zhaopx
- * Date: 2019/9/10
- * Time: 14:10
- *
- * </pre>
- *
- * @author zhaopx
- */
- public class JaxbTest {
- @Test
- public void saveXmlTest() {
- User user = new User("陈本布衣", 2018, "超级管理员","瞎哔哔");
- File file = new File("user.xml");
- try {
- JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
- Marshaller marshaller = jaxbContext.createMarshaller();
- //格式化输出,即按标签自动换行,否则就是一行输出
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
- //设置编码(默认编码就是utf-8)
- marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
- //是否省略xml头信息,默认不省略(false)
- marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);
- marshaller.marshal(user, file);
- } catch (JAXBException e) {
- e.printStackTrace();
- }
- }
- @Test
- public void getUserTest() {
- File file = new File("user.xml");
- try {
- JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
- Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
- User user = (User) unmarshaller.unmarshal(file);
- System.out.println(user.toString());
- } catch (JAXBException e) {
- e.printStackTrace();
- }
- }
- }
|