注意: 我是EclipseLink JAXB (MOXy)负责人,也是JAXB 2 (JSR-222)专家组的成员。
下面是一个应该有所帮助的完整示例。
jaxb.properties
要将 MOXy 指定为您的 JAXB 提供程序,您需要在与域模型相同的包中添加一个名为jaxb.properties
以下条目的文件。
javax.xml.bind.context.factory = org.eclipse.persistence.jaxb.JAXBContextFactory
FindRequestDTO
package forum9881188;
import java.io.*;
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.*;
@XmlRootElement(name = "UseCaseView")
public class FindRequestDTO implements Serializable {
private static final long serialVersionUID = 5528726225975606325L;
private ApiRequestDTO apiRequest;
@XmlPath("FindCandidates/CandidatesRequest/APIRequest")
public ApiRequestDTO getAPIRequest() {
return apiRequest;
}
public void setAPIRequest(ApiRequestDTO apiRequest) {
this.apiRequest = apiRequest;
}
}
ApiRequestDTO
package forum9881188;
public class ApiRequestDTO {
}
演示
package forum9881188;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(FindRequestDTO.class);
FindRequestDTO fr = new FindRequestDTO();
fr.setAPIRequest(new ApiRequestDTO());
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(fr, System.out);
}
}
输出
<?xml version="1.0" encoding="UTF-8"?>
<UseCaseView>
<FindCandidates>
<CandidatesRequest>
<APIRequest/>
</CandidatesRequest>
</FindCandidates>
</UseCaseView>
了解更多信息
更新
如果由于某种原因您无法获得 MOXy 的实现JAXBContext
,您始终可以使用本机 API 进行引导。使用本机 API 时,您不需要该jaxb.properties
文件:
package forum9881188;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextFactory;
public class Demo {
public static void main(String[] args) throws Exception {
//JAXBContext jc = JAXBContext.newInstance(FindRequestDTO.class);
JAXBContext jc = JAXBContextFactory.createContext(new Class[] {FindRequestDTO.class}, null);
FindRequestDTO fr = new FindRequestDTO();
fr.setAPIRequest(new ApiRequestDTO());
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(fr, System.out);
}
}