注:我是EclipseLink JAXB (MOXy)鉛和JAXB (JSR-222)專家小組的成員。
以下是如何使用MOXy的外部映射文件擴展名支持此用例。
元數據XML 1
我們將使用標準的JAXB註釋到Gobj
類映射到第一個XML表示。
package forum17652921;
import javax.xml.bind.annotation.*;
@XmlRootElement(name="xml1")
@XmlAccessorType(XmlAccessType.FIELD)
public class Gobj {
@XmlElement(name="a")
String fName;
@XmlElement(name="b")
String lName;
@XmlElement(name="c")
String id;
}
元數據XML 2
我們將使用莫西的外部映射文件相同的類映射到第二XML表示。默認情況下,映射文檔用於擴充註釋提供的元數據。如果我們將xml-metadata-complete
標誌設置爲true,那麼您可以完全替換該元數據。
<?xml version="1.0"?>
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="forum17652921"
xml-accessor-type="FIELD"
xml-mapping-metadata-complete="true">
<java-types>
<java-type name="Gobj">
<xml-root-element name="xml2"/>
<java-attributes>
<xml-element java-attribute="fName" xml-path="d/name/my/text()"/>
<xml-element java-attribute="lName" name="e"/>
<xml-element java-attribute="id" name="f"/>
</java-attributes>
</java-type>
</java-types>
</xml-bindings>
演示
在演示代碼下面有的JAXBContext
兩個實例。我們將使用第一個將XML表示1讀取到Gobj
的實例。然後,我們將使用第二個JAXBContext
將相同的Gobj
實例編組爲第二個XML表示。
package forum17652921;
import java.io.File;
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc1 = JAXBContext.newInstance(Gobj.class);
Unmarshaller unmarshaller = jc1.createUnmarshaller();
File xml = new File("src/forum17652921/xml1.xml");
Gobj gobj = (Gobj) unmarshaller.unmarshal(xml);
Map<String, Object> properties = new HashMap<String, Object>(1);
properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "forum17652921/oxm.xml");
JAXBContext jc2 = JAXBContext.newInstance(new Class[] {Gobj.class}, properties);
Marshaller marshaller = jc2.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(gobj, System.out);
}
}
xml1。XML
<xml1>
<a>hello</a>
<b>shreyas</b>
<c>123</c>
</xml1>
輸出
<?xml version="1.0" encoding="UTF-8"?>
<xml2>
<d>
<name>
<my>hello</my>
</name>
</d>
<e>shreyas</e>
<f>123</f>
</xml2>
更多信息
謝謝了很多Blaise,這正是我需要的 –
THANKs很多Blaise,我在我的環境中嘗試過,但是我得到了「javax.xml.bind.JAXBException:property」eclipselink.oxm.metadata-source 「不支持」的預期。 –
我創建了jaxb.properties並將它放在我的模型類上,我猜它沒有被拾取。我仍然得到相同的不支持excepition。 –