EclipseLink JAXB (MOXy)(我是技術負責人)有一個XML映射文件。對於您的示例映射文件將是:
綁定。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
要使用莫西作爲JAXB實現需要包括jaxb.properties與您的文件具有以下條目的模型類:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
注意
此示例使用在即將到來的EclipseLink 2.2發行版中的簡化引導。對於使用的EclipseLink 2.1的例子看看:
我已經有了Java類和XML文件。不能改變這一點,所以我需要用一個描述符將它們粘合在一起,說明「this goes here」。生成東西並不是一個真正的選擇。感謝您的回答! – user1010 2010-12-08 09:27:36
我想我會試試Castor的「映射模式」。似乎沒有任何代碼生成就做我所需要的。再次感謝。 – user1010 2010-12-09 08:34:56