XML 파싱을 하기 위해서 Simple Framework 라이브러리를 사용해봤는데 은근 애 좀 먹었다.
일단 gradle에 추가할 때,
compile('org.simpleframework:simple-xml:2.7.+')
로 추가를 하면 첫 빌드는 성공하지만 그 다음 빌드는 실패를 한다. 찾아보니 아래 코드처럼 추가를 하면 된다.
compile('org.simpleframework:simple-xml:2.7.+'){ exclude module: 'stax' exclude module: 'stax-api' exclude module: 'xpp3' }
XML Response가 왔을 때, 파싱될 객체들만 잘 정의하면 사용하기는 편할 듯 싶은데, 그 객체를 정의하는게 좀 까다롭긴 하다.
아래는 파싱 코드
Serializer serializer = new Persister(); try { RssType rssType = serializer.read(RssType.class, response); Log.d(mTag, "title: " + rssType.getChannel().getItemList().get(0).getTitle()); } catch (Exception e) { e.printStackTrace(); }
객체는 @Root, @Element, @ElementList, @Attribute를 변수에 맞게 사용해주면 된다.
@Element (name = "channel") public class ChannelType { @Element private String title; @Element private String link; @Element private String description; @Element private String lastBuildDate; @Element private String total; @Element private String start; @Element private String display; @ElementList(entry = "item", inline = true) private List itemList; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLastBuildDate() { return lastBuildDate; } public void setLastBuildDate(String lastBuildDate) { this.lastBuildDate = lastBuildDate; } public String getTotal() { return total; } public void setTotal(String total) { this.total = total; } public String getStart() { return start; } public void setStart(String start) { this.start = start; } public String getDisplay() { return display; } public void setDisplay(String display) { this.display = display; } public List getItemList() { return itemList; } public void setItemList(List itemList) { this.itemList = itemList; } }