注意:我是EclipseLink JAXB (MOXy)负责人,也是JAXB (JSR-222)专家组的成员。
由于您希望使用单个类映射到 XML,因此您可以使用 MOXy 的@XmlPath
扩展(参见:http ://blog.bdoughan.com/2010/07/xpath-based-mapping.html )。
信息
import java.util.Calendar;
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlRootElement(name="Info")
@XmlAccessorType(XmlAccessType.FIELD)
public class Info {
@XmlPath("details/arrange/name/text()")
private String name;
@XmlPath("details/arrange/ID/text()")
private int id;
@XmlPath("details/arrange/Date/text()")
private Calendar date;
@XmlPath("details/arrange/LatestDate/Start/text()")
private Calendar start;
@XmlPath("details/arrange/LatestDate/End/text()")
private Calendar end;
@XmlPath("details/arrange/Additional/name/text()")
private String additionalName;
}
jaxb.properties
要将 MOXy 指定为您的 JAXB 提供程序,您需要包含一个jaxb.properties
在与域模型相同的包中调用的文件,其中包含以下条目(请参阅: http ://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as -your.html )。
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
演示
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Info.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum16956564/input.xml");
Info info = (Info) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(info, System.out);
}
}
输入.xml/输出
<?xml version="1.0" encoding="UTF-8"?>
<Info>
<details>
<arrange>
<name>joseph</name>
<ID>12</ID>
<Date>2012-03-25T11:23:42+10:00</Date>
<LatestDate>
<Start>2012-06-25T09:24:59+10:00</Start>
<End>2013-06-25T09:24:59+10:00</End>
</LatestDate>
<Additional>
<name>IVR</name>
</Additional>
</arrange>
</details>
</Info>