달력

52024  이전 다음

  • 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
  • 31

'XStreamMarshaller'에 해당되는 글 1건

  1. 2011.04.30 [Spring oxm] XStreamMarshaller 를 사용하여 XML을 Java 객체로 변환하기
1. XML 데이터
<PARENT>
    <HEAD>
        <RESULT_CODE>00001</RESULT_CODE>
        <RESULT_MESSAGE>success</RESULT_MESSAGE>
    </HEAD>
    <BODY>
        <STATUS>true</STATUS>
    </BODY>
</PARENT>

2. Bean 설정
<bean id="unmarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
    <property name="aliases">
        <props>
            <prop key="PARENT">kr.or.openframework.model.Parent</prop>
        </props>
    </property>
    <property name="autodetectAnnotations" value="true" />
</bean>

3. Repository 소스
@Repository
public class ParentRepository {
    @Resource(name = "unmarshaller")
    private Unmarshaller unmarshaller;
   
    public Object xmlToObject(URL url) {
        InputStream urlInputStream = null;
        try {
            urlInputStream = url.openConnection().getInputStream();
            return unmarshaller.unmarshal(new StreamSource(urlInputStream));
        } catch (IOException e) {
        } finally {
            if (urlInputStream != null) {
                try {
                    urlInputStream.close();
                } catch (IOException e) {
                }
            }
        }
    }
}

4. 모델 클래스
package kr.or.openframework.model;

import com.thoughtworks.xstream.annotations.XStreamAlias;

@XStreamAlias("PARENT")
public class Parent {
    @XStreamAlias("HEAD")
    private Head head;
    @XStreamAlias("BODY")
    private Body body;

    public Head getHead() {
        return head;
    }

    public void setHead(Head head) {
        this.head = head;
    }

    public Body getBody() {
        return body;
    }

    public void setBody(Body body) {
        this.body = body;
    }
}

@XStreamAlias("HEAD")
class Head extends BaseModel {
    @XStreamAlias("RESULT_CODE")
    private String resultCode;
    @XStreamAlias("RESULT_MESSAGE")
    private String resultMessage;

    public String getResultCode() {
        return resultCode;
    }

    public void setResultCode(String resultCode) {
        this.resultCode = resultCode;
    }

    public String getResultMessage() {
        return resultMessage;
    }

    public void setResultMessage(String resultMessage) {
        this.resultMessage = resultMessage;
    }
}
@XStreamAlias("BODY")
class Body {
    @XStreamAlias("STATUS")
    private String status;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status= status;
    }
}

5. 결과 출력
kr.or.openframework.model.Parent@e72f0c[
  head=kr.or.openframework.model.Head@12eabae[ 
  resultCode=00001
  resultMessage=success
]
  body=kr.or.openframework.model.Body@10948cf[
  status=true
]
]


Posted by fromm0
|