This article answers a common question: “How to read a XML file in a web application?”
I was once in the situation, where I had to find a solution for this problem. So, I would like to share my solution with you.
To demonstrate the solution, I have attached an Eclipse project. I have used Eclipse Galileo under Windows Vista.
This project is a servlet, which reads a XML file, processes the content and finally prints out the content.
The following steps demonstrates the solution.
1 .The XML – File (excerpt)
<person>
<firstName>Anna</firstName>
<lastName>Sazi</lastName>
</person>
2 . Read in the XML File:
InputStream inputStream = ctx.getResourceAsStream("/WEB-INF/" + XML_FILE_NAME);
Explanation: By this method you obtain an InputStream – Object. It turned out that the file must be located below the WEB-INF folder of the web application. Any other subfolder is also possible.
3. Get a Document – Object
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(inputStream);
Explanation: The aim of these three commands is to get an representation of the XML file which has been read in during the step 1.
4. Get the values from the node
NodeList firstNameList = element.getElementsByTagName("firstName");
Element firstNameElement = (Element) firstNameList.item(0);
NodeList textFirstNameList = firstNameElement.getChildNodes();
person.setFirstName(((Node) textFirstNameList.item(0)).getNodeValue().trim());
Explanation: This code gets the value of the node whose name is “firstName”. It also adds the obtained value to an “Person” – Object.
5. Print out the values
for(Person person : personList)
{
out.println("<tr>");
out.println("<td>" + person.getFirstName() + "</td>");
out.println("<td>" + person.getLastName() + "</td>");
out.println("</tr>");
}
Explanation: This code prints out the values from the Person
list.
For the full code, feel free to download the attached project.
To invoke the servlet, you need to enter “<domain>/XmlReadingExample” into the address bar of your browser.