본문 바로가기

프레임워크

[Castor] null값을 갖는 객체의 속성을 XML로 변환하기(Marshaling)

"옳바른 성장과 따뜻한 나눔"

Castor에서 null값을 갖는 속성은 무시된다. 즉, XML로 변환되지 않는다.
그런데 가끔 우리는 해당 엘리먼트가 반드시 존재해야 할 때가 있다.
즉, 값이 존재하지 않는 빈 태그가 필요한 경우 어떻게 할 것인가?

Castor 1.3(castor-xml-1.3, castor-core-1.3) 사용

Castor 0.9.6 에서부터 지원하기 시작한 nillable을 이용하거나 핸들러를 만들 수 있다.
그러나 핸들러를 별도로 만들경우 모든 경우에 대한 핸들러를 만들어 줘야만 하기 때문에 현실적으로 어렵다. 그러므로 여기에서는 nillable을 이용한 방법을 알아본다.

아래와 같은 객체와 Castor맵핑파일이 있을 때

/**
 * 간단한 개인정보
 */
public class Person implements java.io.Serializable {
    /** UID */
    private static final long serialVersionUID = -1318223135327041667L;

    /** 이름 */
    private String name;
    /** 나이 */
    private int age;
    /** 주소 */
    private String address;

    /**
     * 기본생성자
     */
    public Person() {
        //
    }

    /**
     * 생성자
     * @param name 이름
     * @param age 나이
     * @param address 주소
     */
    public Person(String name, int age, String address) {
        this.name = name;
        this.age = age;
        this.address = address;
    }

    // Getters and Setters

}


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapping PUBLIC "-//EXOLAB/Castor Mapping DTD Version 1.0//EN" "http://castor.exolab.org/mapping.dtd">
<mapping>
  <class name="mypackage.Person">
    <map-to xml="Person" />
    <field name="name" type="java.lang.String" nillable="true" required="true">
      <bind-xml name="Name" node="element" />
    </field>
    <field name="age" type="int">
      <bind-xml name="Age" node="element" />
    </field>
    <field name="address" type="java.lang.String">
      <bind-xml name="Address" node="element" />
    </field>
  </class>
</mapping>


만약 Person persion = new Person(null, 0 , null); 와 같은 인스턴스를 XML로
변환하면 아래와 같다.

<?xml version="1.0" encoding="UTF-8"?>
<Person>
  <Name xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true" />
  <Age>0</Age>
</Person>

즉, name은 필수 요소이면서 널을 허용하므로 엘리먼트를 만들고 address는 널이므로 엘리먼트를 생성하지 않는다.

여기에서 주의할 것은 nillable 하나만 사용할 경우 required의 기본값이 false이므로 위와 같이 생성되지 않는다는 것이다. 그러므로 빈태그를 생성하기 위해서는 반드시 nillable과 required를 같이 적용해야만 한다.