EclipseLink JAXB (MOXy) (я технический руководитель) содержит файл сопоставления XML.Для вашего примера файл сопоставления будет иметь вид:
binding.xml
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="blog.bindingfile">
<java-types>
<java-type name="Customer">
<xml-root-element/>
<xml-type prop-order="person street city state zip phone"/>
</java-type>
<java-type name="Person">
<xml-type prop-order="customerNumber firstName lastName"/>
<java-attributes>
<xml-element java-attribute="customerNumber" name="cust-num"/>
<xml-element java-attribute="firstName" name="first-name"/>
<xml-element java-attribute="lastName" name="last-name"/>
</java-attributes>
</java-type>
</java-types>
</xml-bindings>
Модель домена
Это будет сопоставлятьследующие классы:
package blog.bindingfile;
public class Customer {
public Person person;
public String street;
public String city;
public String state;
public Integer zip;
public String phone;
}
package blog.bindingfile;
public class Person {
public int customerNumber;
public String firstName;
public String lastName;
}
XML
В / из следующего XML:
<?xml version="1.0" encoding="UTF-8"?>
<customer>
<person>
<cust-num>123456789</cust-num>
<first-name>John</first-name>
<last-name>Smith</last-name>
</person>
<street>12345 Happy Lane</street>
<city>Plunk</city>
<state>WA</state>
<zip>98059</zip>
<phone>888.555.1234</phone>
</customer>
Демонстрационный код
Как показывают:
package blog.bindingfile;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.eclipse.persistence.jaxb.JAXBContextFactory;
public class Demo {
public static void main(String[] args) throws Exception {
Map<String, Object> properties = new HashMap<String, Object>(1);
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, new File("binding.xml"));
JAXBContext jc = JAXBContext.newInstance("blog.bindingfile", Customer.class.getClassLoader() , properties);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Customer customer = (Customer) unmarshaller.unmarshal(new File("input.xml"));
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(customer, System.out);
}
}
jaxb.properties
Чтобы использовать MOXy в качестве реализации JAXB, вам необходимо включить файл jaxb.propertiesс классами модели со следующей записью:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Примечание
В этом примере используется упрощенная начальная загрузка, доступная в следующем выпуске EclipseLink 2.2.Пример использования EclipseLink 2.1: