从BaseX服务器执行的XQuery中我得到一个结果:
<ProtocolloList>
<protocollo>
<numero>1</numero>
<data>2014-06-23</data>
<oggetto/>
<destinatario/>
<operatore/>
</protocollo>
...
</ProtocolloList>
我需要使用JAXB将此结果转换为Protocollo对象列表,以便我可以使用JList显示它们。因此,在其中一个讨论here之后,我宣布了以下课程:
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "protocollo")
public class Protocollo {
private int numero;
private String data;
private String oggetto;
private String destinatario;
private String operatore;
public Protocollo(String d, String o, String des, String op) {
this.data = d;
this.oggetto = o;
this.destinatario = des;
this.operatore = op;
}
public Protocollo() {
}
@XmlElement
public int getNumero() {
return numero;
}
public void setNumero(int numero) {
this.numero = numero;
}
@XmlElement
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
@XmlElement
public String getOggetto() {
return oggetto;
}
public void setOggetto(String oggetto) {
this.oggetto = oggetto;
}
@XmlElement
public String getDestinatario() {
return destinatario;
}
public void setDestinatario(String destinatario) {
this.destinatario = destinatario;
}
@XmlElement
public String getOperatore() {
return operatore;
}
public void setOperatore(String operatore) {
this.operatore = operatore;
}
}
和
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "ProtocolloList")
public class ProtocolloList {
@XmlElementWrapper(name = "ProtocolloList")
@XmlElement(name = "protocollo")
private ArrayList<Protocollo> ProtocolloList;
public ArrayList<Protocollo> getProtocolloList() {
return ProtocolloList;
}
public void setProtocolloList(ArrayList<Protocollo> protocolloList) {
ProtocolloList = protocolloList;
}
}
最后我执行了这样的转换:
JAXBContext jaxbContext = JAXBContext.newInstance(Protocollo.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader(this.resultXML);
protocolli = (ProtocolloList) unmarshaller.unmarshal(reader);
我继续得到这个例外:
unexpected element (uri:"", local:"ProtocolloList"). Expected elements are <{}protocollo>
我想我用注释犯了一些错误。 你能帮忙吗?
答案 0 :(得分:9)
对于您的用例,您不需要@XmlElementWrapper
注释。这是因为ProtocolList
元素对应于您的@XmlRootElement
注释。然后,您需要在属性上使用@XmlElement
注释来获取每个列表项。
@XmlRootElement(name = "ProtocolloList")
public class ProtocolloList {
private ArrayList<Protocollo> ProtocolloList;
@XmlElement(name = "protocollo")
public ArrayList<Protocollo> getProtocolloList() {
return ProtocolloList;
}
}
注意:强>
默认情况下,您应该注释该属性。如果您想要注释字段,则应将@XmlAccessorType(XmlAccessType.FIELD)
放在班级上。
您需要确保JAXBContext
知道根类。您可以将JAXBContext
创建代码更改为以下内容:
JAXBContext jaxbContext = JAXBContext.newInstance(ProtocolloList.class);