Java @XmlElement没有命名空间时为null
我使用Jaxb解组器将xmpp服务器的部分响应映射到java对象 Test.javaJava @XmlElement没有命名空间时为null,java,jaxb,Java,Jaxb,我使用Jaxb解组器将xmpp服务器的部分响应映射到java对象 Test.java public class Test { public static void main(String[] args) throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(MucUser.class); Unmarshaller unmarshaller = jaxbContext
public class Test {
public static void main(String[] args) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(MucUser.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
ByteArrayInputStream bais = new ByteArrayInputStream((
"<x xmlns='http://jabber.org/prot" +
"ocol/muc#user'><item role='moderator'" +
" affiliation='owner'/></x>").getBytes());
MucUser mucUser = (MucUser) unmarshaller.unmarshal(bais);
System.out.println(mucUser.getItem());
}
}
Item.java
@XmlAccessorType(XmlAccessType.FIELD)
public class Item {
@XmlAttribute(name = "role")
private String role;
@XmlAttribute(name = "affiliation")
private String affiliation;
// getters and setters without annotations
}
我不使用ObjectFactory.java和package-info.java。字段item
未被解组,并且mucUser.getItem()
返回null。但当我在Test.java中显式地将namespacetst
添加到元素
,并修改MucUser.java以使用注释@xmlement(name=“item”,namespace=“tst”)
时,效果很好
但是,我不能根据自己的意愿修改该字符串,它是协议的一部分
如何正确映射MucUser类中的
项
?在XML中,您正在“x”元素中设置默认名称空间。包含的元素使用此命名空间。因此,项应使用与Mcuser相同的命名空间谢谢。我将MucUser.java
中的注释修改为@xmlement(name=“item”,namespace=”http://jabber.org/protocol/muc#user”
,它开始按预期工作。
@XmlAccessorType(XmlAccessType.FIELD)
public class Item {
@XmlAttribute(name = "role")
private String role;
@XmlAttribute(name = "affiliation")
private String affiliation;
// getters and setters without annotations
}