XmlAdapter
以下は、これを行うために を活用できる方法です。
XmlAdapter (LastNameAdapter)
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class LastNameAdapter extends XmlAdapter<LastNameAdapter.AdaptedLastName, String> {
@XmlType(propOrder={"lastname", "birthdate"})
public static class AdaptedLastName {
public String lastname;
public String birthdate;
}
private String birthdate;
public LastNameAdapter() {
}
public LastNameAdapter(String birthdate) {
this.birthdate = birthdate;
}
@Override
public String unmarshal(AdaptedLastName v) throws Exception {
return v.lastname;
}
@Override
public AdaptedLastName marshal(String v) throws Exception {
AdaptedLastName adaptedLastName = new AdaptedLastName();
adaptedLastName.lastname = v;
adaptedLastName.birthdate = birthdate;
return adaptedLastName;
}
}
外部メタデータ (oxm.xml)
<?xml version="1.0"?>
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="forum19641824">
<java-types>
<java-type name="Customer">
<xml-root-element/>
<xml-type prop-order="firstname lastname"/>
<java-attributes>
<xml-element java-attribute="firstname"/>
<xml-element java-attribute="lastname" xml-path=".">
<xml-java-type-adapter value="forum19641824.LastNameAdapter"/>
</xml-element>
</java-attributes>
</java-type>
</java-types>
</xml-bindings>
デモ
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
public class Demo {
public static void main(String[] args) throws Exception {
Map<String, Object> properties = new HashMap<String, Object>(1);
properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "forum19641824/oxm.xml");
JAXBContext jc = JAXBContext.newInstance(new Class[] {Customer.class}, properties);
Customer customer = new Customer();
customer.setFirstname("Tony");
customer.setLastname("Stark");
Marshaller marshaller = jc.createMarshaller();
marshaller.setAdapter(new LastNameAdapter("01.01.1990"));
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(customer, System.out);
}
}
出力
<?xml version="1.0" encoding="UTF-8"?>
<customer>
<firstname>Tony</firstname>
<lastname>Stark</lastname>
<birthdate>01.01.1990</birthdate>
</customer>