当我尝试解析这些消息时,我没有收到“公告”:
<?xml version="1.0" encoding="UTF-8"?>
<message messageType="SUBSCRIBER" messageName="ANNOUNCEMENT">
<announcement time="12:30">
Lunchtime!
</announcement>
<announcement time="32:00">
Good night ...
</announcement>
<errorText>Phone number missing, subscriber: Dick</errorText>
</message>
JAXB Java类看起来非常简单。并基于类似的消息工作。在这种情况下,差异似乎是我可以在主块中有两种不同类型的嵌套元素(XmlElement)。
下面的代码实际上解析了XML,但它没有调用Announcement。 setMessageText ()方法。虽然我可以看到time属性是从XML设置的,并且我有一个数组大小= 2的公告,它读取并设置单个errorText XmlElement。 Btw ,我还从代码和XML中删除了标签 - 没有改变我的messageText的处理方式。欢迎创意!
@XmlRootElement(name = "message")
public class AnnouncementMessage
{
@XmlAttribute
public String getMessageName(){
return this.messageName;
}
public void setMessageName( String name ){
this.messageName = name;
}
@XmlAttribute
public String getMessageType(){
return messageType;
}
public void setMessageType( String newMessageType ){
this.messageType = newMessageType;
}
@XmlElement(name = "errorText")
public String getErrorText(){
return errorText;
}
public void setErrorText( String newMsg ){
this.errorText = newMsg;
}
private List<Announcement> announcements = new ArrayList<>();
@XmlElement(name = "announcement")
public List<Announcement> getAnnouncements(){
return this.announcements;
}
public void setAnnouncements( List<Announcement> newAnnouncements ){
this.announcements = newAnnouncements;
}
}
宣传课程:
@XmlRootElement(name = "announcement")
public class Announcement
{
private String messageText = "";
private String time = "12:00";
XmlAttribute(name ="time")
public String getTime(){
return this.time;
}
public void setTime( String newMsg ){
this.messageText = time;
}
@XmlElement(name="announcement")
public String getMessageText(){
return this.messageText;
}
public void setMessageText( String newMsg ){
this.messageText = newMsg;
}
Announcement(){
}
}
在XmlElement中使用name参数似乎没什么区别。我提前致谢。
答案 0 :(得分:2)
使用@XmlValue
注释添加消息文本:
@XmlValue
public String getMessageText(){
return this.messageText;
}
此外,正如OP在this related answer中所述,@XmlAccessorType(XmlAccessType.NONE)
类需要Announcement
,如果它包含未映射到XML或来自XML的getter / setter对,并且不要t有一个@XmlTransient
注释。