このユース ケースでは XmlAdapter を使用できます。
input1.xml
がない場合は、setter を呼び出しません。または、setter を呼び出す必要がある場合は、null を渡します。
<?xml version="1.0" encoding="UTF-8"?>
<root>
<child/>
</root>
input2.xml
が存在するが空の場合、空のリストをセッターに渡します。
<?xml version="1.0" encoding="UTF-8"?>
<root>
<child>
<foos/>
</child>
</root>
input3.xml
1 つ以上の子要素がある場合は、入力済みのリストを渡します。
<?xml version="1.0" encoding="UTF-8"?>
<root>
<child>
<foos>
<foo>Hello World</foo>
</foos>
</child>
</root>
根
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlRootElement
public class Root {
private Child child;
@XmlJavaTypeAdapter(ChildAdapter.class)
public Child getChild() {
return child;
}
public void setChild(Child child) {
this.child = child;
}
}
子
import java.util.List;
public class Child {
private List<String> strings;
public List<String> getStrings() {
return strings;
}
public void setStrings(List<String> strings) {
System.out.println("setStrings");
this.strings = strings;
}
}
子アダプタ
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class ChildAdapter extends XmlAdapter<ChildAdapter.AdaptedChild, Child> {
public static class AdaptedChild {
public Foos foos;
}
public static class Foos {
public List<String> foo;
}
@Override
public Child unmarshal(AdaptedChild adaptedChild) throws Exception {
Child child = new Child();
Foos foos = adaptedChild.foos;
if(null != foos) {
List<String> foo = foos.foo;
if(null == foo) {
child.setStrings(new ArrayList<String>());
} else {
child.setStrings(foos.foo);
}
}
return child;
}
@Override
public AdaptedChild marshal(Child child) throws Exception {
AdaptedChild adaptedChild = new AdaptedChild();
List<String> strings = child.getStrings();
if(null != strings) {
Foos foos = new Foos();
foos.foo = strings;
adaptedChild.foos = foos;
}
return adaptedChild;
}
}
デモ
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Root.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Object o;
o = unmarshaller.unmarshal(new File("input1.xml"));
marshaller.marshal(o, System.out);
o = unmarshaller.unmarshal(new File("input2.xml"));
marshaller.marshal(o, System.out);
o = unmarshaller.unmarshal(new File("input3.xml"));
marshaller.marshal(o, System.out);
}
}
出力
<?xml version="1.0" encoding="UTF-8"?>
<root>
<child/>
</root>
setStrings
<?xml version="1.0" encoding="UTF-8"?>
<root>
<child>
<foos/>
</child>
</root>
setStrings
<?xml version="1.0" encoding="UTF-8"?>
<root>
<child>
<foos>
<foo>Hello World</foo>
</foos>
</child>
</root>