how to parse xml using sax parser? i struggle to parse the author section part into array. i follow example from here http://ganeshtiwaridotcomdotnp.blogspot.com/2011/08/xml-parsing-using-saxparser-with.html
XML
<catalog>
<book id="001" lang="ENG">
<isbn>23-34-42-3</isbn>
<regDate>1990-05-24</regDate>
<title>Operating Systems</title>
<publisher country="USA">Pearson</publisher>
<price>400</price>
<authors>
<author>
<name>Ganesh Tiwari</name>
<age>1</age>
</author>
</authors>
</book>
<book id="002">
<isbn>24-300-042-3</isbn>
<regDate>1995-05-12</regDate>
<title>Distributed Systems</title>
<publisher country="Nepal">Ekata</publisher>
<price>500</price>
<authors>
<author>
<name>Mahesh Poudel</name>
<age>2</age>
</author>
<author>
<name>Bikram Adhikari</name>
<age>3</age>
</author>
<author>
<name>Ramesh Poudel</name>
<age>4</age>
</author>
</authors>
</book>
</catalog>
start
public BookSaxParser() {
bookL = new ArrayList<Book>();
authorL = new ArrayList<Author>();
}
public List<Book> printDatas() {
return bookL;
}
@Override
public void startElement(String s, String s1, String elementName, Attributes attributes) throws SAXException {
// if current element is book , create new book
// clear tmpValue on start of element
if (elementName.equalsIgnoreCase("book")) {
bookTmp = new Book();
bookTmp.setId(attributes.getValue("id"));
bookTmp.setLang(attributes.getValue("lang"));
}
if (elementName.equalsIgnoreCase("author")) {
authorTmp = new Author();
}
// if current element is publisher
if (elementName.equalsIgnoreCase("publisher")) {
bookTmp.setPublisher(attributes.getValue("country"));
}
}
@Override
public void endElement(String s, String s1, String element) throws SAXException {
// if end of book element add to list
if (element.equals("book")) {
bookL.add(bookTmp);
}
if (element.equals("authors")) {
bookTmp.setAuthors(authorL);
}
if (element.equals("author")) {
authorL.add(authorTmp);
}
if(element.equalsIgnoreCase("name")){
authorTmp.setName(tmpValue);
}
if(element.equalsIgnoreCase("age")){
authorTmp.setAge(Integer.parseInt(tmpValue));
}
if (element.equalsIgnoreCase("isbn")) {
bookTmp.setIsbn(tmpValue);
}
if (element.equalsIgnoreCase("title")) {
bookTmp.setTitle(tmpValue);
}
if(element.equalsIgnoreCase("price")){
bookTmp.setPrice(Integer.parseInt(tmpValue));
}
if(element.equalsIgnoreCase("regDate")){
try {
bookTmp.setRegDate(sdf.parse(tmpValue));
} catch (ParseException e) {
//System.out.println("date parsing error");
}
}
}
@Override
public void characters(char[] ac, int i, int j) throws SAXException {
tmpValue = new String(ac, i, j);
}
public void endDocument() throws SAXException {
// you can do something here for example send
// the Channel object somewhere or whatever.
}
`
Your code is adding authors to the authorL list as you parse them, and then assigning that same list to each of the books.
To fix this you need to create a new list of authors each time you encounter the Authors element
Something like: