Jyoti Singh
Jyoti Singh

Reputation: 41

How to set XML Attribute inside XML Element in Java Pojo Class - JAVX

How can I get this Output Response?

<Response>
  <Play loop=10>
    https:aws-mp3-file-locaation.com
  </Play>
</Response>

What I implemented:

1. First Try, Created Simple CustomResponse class and set element and attribute inside that class.

@XmlRootElement(name = "Response")
public CustomResponse{
  private String play;
  private int loop;
  
  
  @XmlElement(name = "Play")
  public String getPlay() {
    return play;
  }

  public void setPlay(String play) {
    this.play = play;
  }

  
  @XmlAttribute(name = "loop")
  public String getLoop() {
    return loop;
  }

  public void setLoop(String loop) {
    this.loop = loop;
  }
}

This is returning the loop value as a response attribute.

<Response loop=10>
  <Play>
    https:aws-mp3-file-locaation.com
  </Play>
</Response>

2. On the second Try, Created a Simple CustomResponse class and Play class. Here I call play inside CustomResponse and In Play.java I already define the element and attribute inside.

@XmlRootElement(name = "Response")
public CustomResponse{
  private Play play;
  
  
  @XmlElement(name = "Play")
  public Play getPlay() {
    return play;
  }

  public void setPlay(Play play) {
    this.play = play;
  }
}
@XmlRootElement(name = "Play")
public PlayResponse{
  private String play;
  private int loop;
  
  
  @XmlElement(name = "play")
  public String getPlay() {
    return play;
  }

  public void setPlay(String play) {
    this.play = play;
  }

  
  @XmlAttribute(name = "loop")
  public String getLoop() {
    return loop;
  }

  public void setLoop(String loop) {
    this.loop = loop;
  }
}

This is returning

<Response>
  <Play>
    <play loop=10>
      https:aws-mp3-file-locaation.com
    </play>
  </Play>
</Response>

Upvotes: 1

Views: 910

Answers (0)

Related Questions