While working on a small requirement, I had to write a small piece of code that can parse an XML file in Java. Although there are number of libraries available in Java which does this task efficiently, I ended up in using normal Java XML parsing using org.w3c.dom parser.
You may want to copy this code and customize it to your to fit it for your need.
Following is the sample XML file that I used.
XML File
Source Code of XML Parser
Following is the source code of sample XML parser in Java that I used to parse sample XML file.
package net.viralpatel.java.xmlparser;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XMLParser {
public void getAllUserNames(String fileName) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
File file = new File(fileName);
if (file.exists()) {
Document doc = db.parse(file);
Element docEle = doc.getDocumentElement();
// Print root element of the document
System.out.println("Root element of the document: "
+ docEle.getNodeName());
NodeList studentList = docEle.getElementsByTagName("student");
// Print total student elements in document
System.out
.println("Total students: " + studentList.getLength());
if (studentList != null && studentList.getLength() > 0) {
for (int i = 0; i < studentList.getLength(); i++) {
Node node = studentList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
System.out
.println("=====================");
Element e = (Element) node;
NodeList nodeList = e.getElementsByTagName("name");
System.out.println("Name: "
+ nodeList.item(0).getChildNodes().item(0)
.getNodeValue());
nodeList = e.getElementsByTagName("grade");
System.out.println("Grade: "
+ nodeList.item(0).getChildNodes().item(0)
.getNodeValue());
nodeList = e.getElementsByTagName("age");
System.out.println("Age: "
+ nodeList.item(0).getChildNodes().item(0)
.getNodeValue());
}
}
} else {
System.exit(1);
}
}
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {
XMLParser parser = new XMLParser();
parser.getAllUserNames("c:\\test.xml");
}
}
Following is the output of our XML parser.
Program Output
Root element of the document: students
Total students: 3
==============================
Name: John
Grade: B
Age: 12
==============================
Name: Mary
Grade: A
Age: 11
==============================
Name: Simon
Grade: A
Age: 18
You can customise this code for your input XML file.
There is bug or bad display at line 33.
if (studentList != null &amp;amp;&amp;amp; studentList.getLength() > 0) {
Thanks JLemire, I have updated the source and removed the typo error.
Hi How to read this XML file and store it into HashSet?
You want want to look at vtd-xml, the latest and most advanced parsing/indexing/XPath engine that offers a lot of cool features
vtd-xml
i have made one project in eclipse for reading xml file, i have write one function for that
function readXMLFile(){
alert(“calling”);
alert(“DocumentBuildFactory instance”);
alert(“Reading xml file”);
alert(“normalize”);
alert(nodeName);
}
until the normalize it was working fine but when its try to fetch node name it will shows nothing
could anybody help me to solve it?
and one more thing where should i put xml file to read it from java file
This is what i meaned by concepting Xml parsing in Java, great stuff!
Perfect!!
Thanks man, It was very useful.
Thanks.. Very informative..
How do you parse this xml file.
Ishan
cards
notes
dice
50 50 10
offices
Connor
notes
dice
cards
10 10 10
security room
Thanks for the tutorial. After going through several blogs including yours, I wrote a utility class to handle all XML related activities. Just thought it might be helpful to anyone trying to do basic stuff with XML.
http://sridharprabhakartechramblings.blogspot.in/2012/10/xml-parsing-made-easy.html
hi,
this code is ok for reading the xml file given the particular tag name(specified). but to read xml file data which consist of dynamic tags its not possible. can u help me out in getting the tag value dynamically and reading the xml file
hi
even i wanted to read xml file dynamically. can someone help me out in this.
Very useful thanks .
I copy the codes into a new project in itellij
and I get this
org.xml.sax.SAXParseException: Content is not allowed in prolog.
[Fatal Error] :1:1: Content is not allowed in prolog.
Process finished with exit code 0
I’m new to Java, may you help me?
thanks!
Hi,
I want to read multiple XML files dynamically … can anybody help ?
Thanks
I need to create a java program wich connects to a database, reads the entire database and generate a xml with the databased mapped… any idea ?
Sir, I have a xml file from that i have to store id value , name value and days value in collection so later i can use that… can you tell me the way..?
Sorry for type
and output should be
Can you drive me the requirement in a question below?
Link: http://stackoverflow.com/questions/24112813/how-to-read-xml-file-using-sax-dom-parser-in-java
File not Found!!!!!
can u please tell me how to give input .xml file directory
i know this is a simple question but i am new to this
Is there any ways to read this type of .xml file
i want to get parameter value according to the parameter name
If any thoughts please let me know.
Hi,
I have this xml
From this xml, I would only want to get the type (i.e., NPSI, NPSI_PM25_3HR) and the value attribute. How can I be able to parse it in java?
Hope you can help me on this. Thanks in advance.
Nice article
Thanks a lot. This piece of code has made my day.
Hi.. This is a fantastic Article..
Further on this, could you please help on how to store the above output into a database(table having count of students, name, age, etc.) ? Waiting for your response !
Thoughtful ! I learned a lot from the points – Does anyone know where my assistant can access a template a form document to edit ?
My XML is very unstructured. Can you help me with a code to parse the very large unstructured xml?