Spring boot study/8. ETC..

Java JAXB Marshalling / UnMarshalling

dudwns3625 2021. 6. 9. 16:36
728x90
반응형
SMALL

Java JAXB Marshalling / UnMarshalling

1. Marshalling (POJO to xml)

  • Value Object Class

    @Setter  
    @XmlRootElement  
    public class TestValue {  
     @XmlElement  
    public String name;  
     @XmlElement  
    public int age;  
    }
  • Marshalling

    TestValue testValue = new TestValue();  
    testValue.setAge(30);  
    testValue.setName("name");  
    JAXBContext context = JAXBContext.newInstance(TestValue.class);  
    Marshaller marshaller = context.createMarshaller();  
    marshaller.marshal(testValue, new File("test.xml"));
  • 위에서 생성한 test.xml 파일의 내용

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <testValue>
     <name>name</name>
     <age>30</age>
    </testValue>
  • Unmarshalling ( xml to POJO)

    TestValue testValue = new TestValue();  
    testValue.setAge(30);  
    testValue.setName("name");  
    File file = new File("test.xml");  
    JAXBContext context = JAXBContext.newInstance(TestValue.class);  
    Unmarshaller unmarshaller = context.createUnmarshaller();  
    TestValue testObject = (TestValue) unmarshaller.unmarshal(file);
728x90
반응형
LIST