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.
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
Following is the output of our XML parser.
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.
Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…
Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…
Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…
1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…
GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…
1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…
View Comments
There is bug or bad display at line 33.
if (studentList != null && 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!
[code language="java"]
//To simplify further
import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class XMLReader{
public static void main (String argv []){
String[] TagNames = {"first","last","age"}; // Enter the node name as elements in an array
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("C:\\JavaTesting\\file.xml"));// path of the xml file
NodeList list = doc.getElementsByTagName("*");
System.out.println("XML Elements: ");
for (int i=0; i<list.getLength(); i++) {
// Get element
Element element = (Element)list.item(i);
System.out.println(element.getNodeName());
}
// 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);
for(int s=0; s<listOfPersons.getLength() ; s++){
Node firstPersonNode = listOfPersons.item(s);
if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
Element firstPersonElement = (Element)firstPersonNode;
for (int i = 0; i < TagNames.length; i++) {
NodeList firstNameList = firstPersonElement.getElementsByTagName(TagNames[i]);
Element firstNameElement = (Element)firstNameList.item(0);
NodeList textFNList = firstNameElement.getChildNodes();
System.out.println(TagNames[i]+" : " + ((Node)textFNList.item(0)).getNodeValue().trim());
}
}//end of if clause
}//end of for loop with s var
}catch (SAXParseException err) {
System.out.println ("** Parsing error" + ", line "
+ err.getLineNumber () + ", uri " + err.getSystemId ());
System.out.println(" " + err.getMessage ());
}catch (SAXException e) {
Exception x = e.getException ();
((x == null) ? e : x).printStackTrace ();
}catch (Throwable t) {
t.printStackTrace ();
}
//System.exit (0);
}//end of main
}
// Still we can have a generic xml reader with dynamic tag names pick. :)
[/code]
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