티스토리 뷰
.
XStream 간단 예제
Magazine 클래스는 다음을 필드로 가지는 간단한 모델
{int id, String title, String url}
public class XStreamTest {
XStream xstream;
@Before
public void setUp() throws Exception {
xstream = new XStream();
xstream.alias("magazine", Magazine.class);
}
@Test
public void xml을_객체로_변환() throws Exception {
File sut = new File("web/data.xml");
Magazine model = (Magazine)xstream.fromXML(sut);
assertEquals("3,title,url", model.toString());
}
@Test
public void 객체를_xml로_변환() throws Exception {
Magazine sut = new Magazine();
sut.setId(1);
sut.setTitle("title");
sut.setUrl("url");
String xml = xstream.toXML(sut);
Magazine model = (Magazine)xstream.fromXML(xml);
assertEquals("1,title,url", model.toString());
}
@SuppressWarnings("unchecked")
@Test
public void 여러객체를_xml로_변환() throws Exception {
xstream.alias("magazines", List.class);
List<Magazine> sut = new ArrayList<Magazine>();
for (int i = 0; i < 3; i++) {
Magazine m = new Magazine();
m.setId(i);
m.setTitle("title");
m.setUrl("url");
sut.add(m);
}
String xml = xstream.toXML(sut);
List<Magazine> list = (List<Magazine>)xstream.fromXML(xml);
for (int i = 0; i < sut.size(); i++) {
assertEquals(i + ",title,url", list.get(i).toString());
}
}
@SuppressWarnings("unchecked")
@Test
public void 여러개의_속성을_가진_xml을_객체로_변환() throws Exception {
xstream.alias("magazines", List.class);
File xml = new File("web/data2.xml");
List<Magazine> sut = (List<Magazine>)xstream.fromXML(xml);
for (int i = 0; i < sut.size(); i++) {
assertEquals((i + 1) + ",title,url", sut.get(i).toString());
}
}
}
.
.
.
'공부 > Java, JSP' 카테고리의 다른 글
[JSTL] contains (0) | 2014.04.20 |
---|---|
InputStream - String 변환유틸 - org.apache.commons.io.IOUtils (0) | 2014.04.03 |
[자바] HashMap이 ArrayList보다 검색과 삭제시 처리시간이 빠르다. (0) | 2014.02.25 |
[자바] 은행 전산시스템 프로젝트 (0) | 2014.02.20 |
[JSP Tag Library] id masking, count 태그 작성 (0) | 2014.02.18 |