【发布时间】:2018-05-27 11:39:02
【问题描述】:
难以置信有多少关于这个主题的问题。尽管如此,它们都没有帮助我,因为我的理解是这是一个常见错误,我相信我的代码是正确的,因为它与我同事传递给我的另一个项目完全相同。
但是..我有这个错误
unable to marshal type "modules.CollaborationInfo" as an element because it is missing an @XmlRootElement annotation
给定这个类 CollaborationInfo:
package modules;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElementRef;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CollaborationInfo", propOrder = {
"AgreementRef",
"ConversationId"
})
public class CollaborationInfo {
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="AgreementRef")
public static class AgreementRef {
@XmlAttribute
private String pmode;
public String getPmode() {
return pmode;
}
public void setPmode(String pmode) {
this.pmode = pmode;
}
}
@XmlElementRef(name = "AgreementRef")
protected AgreementRef AgreementRef = new AgreementRef();
@XmlElement(name="ConversationId")
protected String ConversationId;
public String getPmode() {
return AgreementRef.getPmode();
}
public void setPmode(String value) {
this.AgreementRef.setPmode(value);
}
public String getConversationId() {
return ConversationId;
}
public void setConversationId(String value) {
this.ConversationId = value;
}
}
作为 main():
public static void main(String[] args) throws Exception{
JAXBContext contextObj = JAXBContext.newInstance(CollaborationInfo.class);
Marshaller marshallerObj = contextObj.createMarshaller();
marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
CollaborationInfo CI = new CollaborationInfo();
CI.setPmode("String1");
CI.setConversationId("String2");
marshallerObj.marshal(CI, new FileOutputStream("C:\\OUT.xml"));
}
我应该可以作为输出(OUT.xml):
<?xml version="1.0" encoding="UTF-8"?>
<CollaborationInfo>
<AgreementRef pmode="String1"/>
<ConversationId>String2</ConversationId>
</CollaborationInfo>
但我就是做不到。 谁能告诉我哪里错了?
(当然,真正的 XML 更长更复杂,但如果我能够让这部分工作,我可能会继续剩下的部分)
【问题讨论】: