-1

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.

Xstian
  • 8,184
  • 10
  • 42
  • 72
  • well ideally it should be another Books class, I can't think of a way other than that but if your concern is an extra public class, maybe you can have a Books class and Book class can be a inner class into that. – Rahul Kumar Jan 04 '17 at 09:02
  • Yup. I can do that but the problem is if I use Inner Class then I can't access Book bean class methods in other classes. I have to write some methods and take help of Books.java class – Sandeep Jan 04 '17 at 09:28
  • Well you can have a public static Book class inside Books class, that way it would be available outside too. – Rahul Kumar Jan 04 '17 at 09:46

1 Answers1

0

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;
}

}