This is the simplest way to read data from an XML file into a Java program. I have also included some basic error checking, so you can directly cut-paste this code with a few changes ofcourse. All you have to do is change the XML tags within the program to match those that are present in your XML file.
Root element of the doc is book Total no of people : 3 First Name : Kiran Last Name : Pai Age : 22 First Name : Bill Last Name : Gates Age : 46 First Name : Steve Last Name : Jobs Age : 40
The Java program to read the above XML file is shown below. Go through the program twice and you will understand all its parts. It may look intimidating at first sight, but believe me its very simple.
// normalize text representation doc.getDocumentElement ().normalize (); System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());
NodeList listOfPersons = doc.getElementsByTagName("person"); int totalPersons = listOfPersons.getLength(); System.out.println("Total no of people : " + totalPersons);
There are better implementations of reading XML files which would work for any XML file. The above one would require a few changes every time the XML tag names change. But this is much more simpler than the other programs.