This post will show you how to parse content from an XML file and convert it to Java Object.
XML file
<Books> <Book> <Id>1</Id> <Name>Java Programming</Name> <Author>Andrew Programming</Author> </Book> <Book> <Id>2</Id> <Name>Python Programming</Name> <Author>Andrew Programming</Author> </Book> </Books>
Book.java
package xmldemo; public class Book { private String id; private String name; private String author; public Book() { } public Book(String id, String name, String author) { this.id = id; this.name = name; this.author = author; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } @Override public String toString() { return "Book{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", author='" + author + '\'' + '}'; } }
Dom parse
package xmldemo; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; import java.util.ArrayList; import java.util.List; public class ReadFromXMLFile { public static void main(String[] args) throws Exception { ReadFromXMLFile instance = new ReadFromXMLFile(); instance.read(); } public void read() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File("Book.xml")); NodeList list = document.getElementsByTagName("Book"); List<Book> bookList = new ArrayList<>(); for (int i = 0; i < list.getLength(); i++) { Element node = (Element) list.item(i); String id = node.getElementsByTagName("Id").item(0).getFirstChild().getNodeValue(); String name = node.getElementsByTagName("Name").item(0).getFirstChild().getNodeValue(); String author = node.getElementsByTagName("Author").item(0).getFirstChild().getNodeValue(); System.out.println("Id: " + id); System.out.println("Name: " + name); System.out.println("Author: " + author); Book book = new Book(id, name, author); bookList.add(book); } System.out.println(); System.out.println(bookList); } }
Output
Id: 1 Name: Java Programming Author: Andrew Programming Id: 2 Name: Python Programming Author: Andrew Programming [Book{id='1', name='Java Programming', author='Andrew Programming'}, Book{id='2', name='Python Programming', author='Andrew Programming'}]