Need help on JAXB

55 views Asked by At

I have an XML which looks like below

<Book>
   <Name>Book1</Name>
   <Cost>20$</Cost>
</Book>

I have used a Bean Class with properties name, cost and successfully unmarshaled the xml file contents to Book bean object.

Now I want to have multiple book objects in the same XML file like below.

<Books>
  <Book>
  ...
  </Book>
  <Book>
  ...
  </Book>

I know that I can create one more class with Name Books.java and have an arraylist of book objects annotated with @XmlElement tag and unmarshall it.

But, I don't want to waste one more public class for doing that. Can anyone let me know if there is any other way of parsing that xml file with JaxB.

Thanks in advance.

1

There are 1 answers

0
Sandeep On

Found the solution..

I can have a class like below. I can use List list; variable member within the same class Book.java instead of using one more public class Books.java.

@XmlRootElement(name = "Books")

@XmlAccessorType(XmlAccessType.FIELD) public class BookBean {

private String name;
private String cost;

@XmlElement(name = "Books")
public List<BookBean> books;

public BookBean(){

}

public BookBean(String s1, String s2){
    name=s1;
    cost=s2;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getCost() {
    return cost;
}

public void setCost(String cost) {
    this.cost = cost;
}

public List<BookBean> getBooks() {
    return books;
}

public void setBooks(List<BookBean> books) {
    this.books = books;
}

}