i am parsing xml file with DOM. Each book can have multiple authors. i can't get access to author tags, what am i doing wrong? how to get child nodes correctly?
This is my java code:
public class DOMBooksReader {
private Book book;
private Author author;
private ArrayList<Book> books = new ArrayList<Book>();
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
public static void main(String[] args) throws ParseException {
DOMBooksReader domBooksReader = new DOMBooksReader();
domBooksReader.parseXml(new File("src\\books.xml"));
}
public void parseXml(File file) throws ParseException {
Document doc = null;
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
doc = documentBuilder.parse(file);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
assert doc != null;
NodeList bookNodes = doc.getElementsByTagName("book");
for (int i = 0; i < bookNodes.getLength(); i++) {
book = new Book();
books.add(book);
}
if (bookElement.getNodeName().equals("authors")) {
NodeList authorNodes = bookElement.getChildNodes();
for (int j = 0; j < authorNodes.getLength(); j++) {
author = new Author();
book.getAuthors().add(author);
}
}
}
}
Here is XML:
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<name>Capacity Planning for Web Performance: Metrics, Models, and Methods</name>
<authors>
<author>
<firstName>Daniel</firstName>
<lastName>Menasce</lastName>
<middleInitial>A</middleInitial>
</author>
<author>
<firstName>Virgilo</firstName>
<lastName>Almeida</lastName>
<middleInitial>F</middleInitial>
</author>
</authors>
...
No comments:
Post a Comment