尝试解析此类消息时,我没有收到“公告”:

 <?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。顺便说一句,我还从代码和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参数似乎没有什么区别。提前谢谢

最佳答案

对消息文本使用@XmlValue批注:

@XmlValue
public  String getMessageText(){
    return this.messageText;
}


另外,如OP在this related answer中所述,如果@XmlAccessorType(XmlAccessType.NONE)包含未从XML映射到XML或从XML映射而没有Announcement批注的getter / setter对,则在@XmlTransient类上需要。

关于java - 如何鼓励JAXB读取XmlElement内容字符串?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25006503/

10-17 01:39