티스토리 뷰

.


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());

}

}


}

.

.

.

댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
글 보관함