注:我是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。 –