Here is a simple way to read your xml using JAXB
Test runner class
public class XmlTest
{
public static void main(String[] args)
{
try
{
File file = new File("d:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Library.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Library library = (Library) jaxbUnmarshaller.unmarshal(file);
for (Book book : library.getBookList())
{
System.out.println(book.getName());
}
}
catch (JAXBException e)
{
e.printStackTrace();
}
}
}
Book class
@XmlType
@XmlAccessorType(XmlAccessType.FIELD)
public class Book
{
@XmlAttribute(name = "name")
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
Library class
@XmlRootElement(name = "Library")
@XmlAccessorType(XmlAccessType.FIELD)
public class Library
{
@XmlAttribute(name = "name")
private String name;
@XmlElement(name = "Book")
private List<Book> bookList;
public List<Book> getBookList()
{
return bookList;
}
public void setBookList(List<Book> bookList)
{
this.bookList = bookList;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
Xml writer
public class XMlWriter
{
public static void main(String[] args)
{
ArrayList<Book> bookArrayList = new ArrayList<Book>();
Book myNewBook = new Book();
myNewBook.setName("My First Copy");
bookArrayList.add(myNewBook);
Library library = new Library();
library.setName("My Name");
library.setBookList(bookArrayList);
try
{
JAXBContext jaxbContext = JAXBContext.newInstance(Library.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
try
{
jaxbMarshaller.marshal(library, new FileOutputStream("D:\\file2.xml"));
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
jaxbMarshaller.marshal(library, System.out);
}
catch (JAXBException e)
{
e.printStackTrace();
}
}
}
The following references used
reading xml document using jaxb
http://www.mkyong.com/java/jaxb-hello-world-example/
*note THIS IS NOT the way to do exception handling