관리 메뉴

나만의공간

Java O/X 매퍼(Mapper)를 사용한 XML 마샬링(Marshalling) 방법 본문

IT/JAVA

Java O/X 매퍼(Mapper)를 사용한 XML 마샬링(Marshalling) 방법

밥알이 2017. 8. 31. 15:59

Java O/X(Object / XML)를 사용한 Unmarshaller 방법


package com.howtodoinjava.jaxb.examples.list;

import java.io.File;
import java.io.StringReader;
import java.util.ArrayList;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class MarshingTest
{
static User userList = new User();
static
{
userList.setUserInfoList(new ArrayList<UserInfo>());

UserInfo user = new UserInfo();
user.setUserId(10001);
user.setFirstName("Lokesh");
user.setLastName("Gupta");
user.setEmail("aaaa@korea.com");

userList.getUserInfoList().add(user);

UserInfo user2 = new UserInfo();
user2.setUserId(20002);
user2.setFirstName("Lokesh222");
user2.setLastName("Gupta333");
user2.setEmail("bbb@korea.com");

userList.getUserInfoList().add(user2);

}

public static void main(String[] args) throws JAXBException
{
marshalingExample();
System.out.println("************************************************");
unMarshalingExample();
}

private static void unMarshalingExample() throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
User user = (User) unmarshaller.unmarshal( new File("\\User\\we\\userList.xml") );
/**
* XML파일을 String 객체에서 가져오기 위해서는 StringReader를 이용한다
**/
String response = "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>"
+"<user>"
+"<userInfoList>"
+"<userId>11</userId>"
+"<firstName>홍</firstName>"
+"<lastName>길동</lastName>"
+"<email>aaaa@korea.com</email>"
+"</userInfoList>"
+"<userInfoList>"
+"<userId>22</userId>"
+"<firstName>진</firstName>"
+"<lastName>라면</lastName>"
+"<email>bbb@korea.com</email>"
+"</userInfoList>"
+"</user>";
StringReader sr = new StringReader(response.toString());
User userStr = (User) unmarshaller.unmarshal(sr);

System.out.println("XML 파일 Mapping 결과======================");
for(UserInfo each : user.getUserInfoList())
{
System.out.println(each.getUserId());
System.out.println(each.getFirstName());
}
System.out.println("String 객체 Mapping 결과======================");
for(UserInfo each : userStr.getUserInfoList())
{
System.out.println(each.getUserId());
System.out.println(each.getFirstName());
}

}

private static void marshalingExample() throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
Marshaller marshaller = jaxbContext.createMarshaller();

marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

marshaller.marshal(userList, System.out);
marshaller.marshal(userList, new File("\\User\\we\\userList.xml"));
} }



'IT > JAVA' 카테고리의 다른 글

Java 편의성 Util #1  (0) 2021.12.17
Project language level은 무엇인가  (0) 2021.12.14
HttpConnection Get / Post 사용법  (0) 2017.08.31
전화번호/핸드폰 자릿수 체크해서 하이픈 넣는법  (0) 2017.07.28
JAVA enum 사용법  (0) 2017.03.16
Comments