Docsity

Parsing XML Files using DOM Parser in Java: A Step-by-Step Guide, Lecture notes of Java Programming

Toggle sidebar
bg1
employees.xml
<employees>
๎˜Š๎˜Š๎˜Š๎˜Š<employee id="111">
๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š<firstName>Lokesh</firstName>
๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š<lastName>Gupta</lastName>
๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š<location>India</location>
๎˜Š๎˜Š๎˜Š๎˜Š</employee>
๎˜Š๎˜Š๎˜Š๎˜Š<employee id="222">
๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š<firstName>Alex</firstName>
๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š<lastName>Gussin</lastName>
๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š<location>Russia</location>
๎˜Š๎˜Š๎˜Š๎˜Š</employee>
๎˜Š๎˜Š๎˜Š๎˜Š<employee id="333">
๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š<firstName>David</firstName>
๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š<lastName>Feezor</lastName>
๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š๎˜Š<location>USA</location>
๎˜Š๎˜Š๎˜Š๎˜Š</employee>
</employees>
1. DOM Parser API
Letโ€™s note down some broad steps to create and use DOM parser to parse a XML file in java.
1.1. Import dom parser packages
We will need to import dom parser packages first in our application.
import org.w3c.dom.*;
import
javax.xml.parsers.*;
import java.io.*;
1.2. Create DocumentBuilder
Next step is to create the DocumentBuilder object.
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
pf3
pf4
pf5
pf8

Partial preview of the text

Download Parsing XML Files using DOM Parser in Java: A Step-by-Step Guide and more Lecture notes Java Programming in PDF only on Docsity!

employees.xml Lokesh Gupta India Alex Gussin Russia David Feezor USA

1. DOM Parser API Letโ€™s note down some broad steps to create and use DOM parser to parse a XML file in java. 1.1. Import dom parser packages We will need to import dom parser packages first in our application. import org.w3c.dom.; import javax.xml.parsers.; import java.io.*; 1.2. Create DocumentBuilder Next step is to create the DocumentBuilder object. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder();

1.3. Create Document object from xml file Read the XML file to Document object. Document document = builder.parse(new File( file )); 1.4. Extract the root element We can get the root element from XML document using below code. Element root = document.getDocumentElement(); 1.5. Examine attributes We can examine the xml element attributes using below methods. element.getAttribute("attributeName") ; //returns specific attribute element.getAttributes(); //returns a Map (table) of names/values 1.6. Examine sub-elements Child elements can inquired in below manner. node.getElementsByTagName("subElementName") //returns a list of sub-elements of specified name node.getChildNodes() //returns a list of all child nodes

2. Read XML with DOM parser In below example code, I am assuming that user is already aware of the structure of employees.xml file (itโ€™s nodes and attributes); So example directly start fetching information and start printing it in console. In real life application, we will use this information for some real purpose rather than printing it on console and leave. //Get Document Builder DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); //Build Document Document document = builder.parse(new File("employees.xml")); //Normalize the XML Structure; It's just too important !! document.getDocumentElement().normalize(); //Here comes the root node Element root = document.getDocumentElement();

dinkar kad dinkar 85 Vaneet Gupta vinni 95 jasvir singn jazz 90 DomParserDemo.java package com.tutorialspoint.xml; import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Element; public class DomParserDemo { public static void main(String[] args) { try { File inputFile = new File("input.txt"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(inputFile); doc.getDocumentElement().normalize(); System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName("student"); System.out.println("----------------------------"); for (int temp = 0 ; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); System.out.println("\nCurrent Element :" + nNode.getNodeName());

if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.println("Student roll no : "

  • eElement.getAttribute("rollno")); System.out.println("First Name : "
  • eElement .getElementsByTagName("firstname") .item( 0 ) .getTextContent()); System.out.println("Last Name : "
  • eElement .getElementsByTagName("lastname") .item( 0 ) .getTextContent()); System.out.println("Nick Name : "
  • eElement .getElementsByTagName("nickname") .item( 0 ) .getTextContent()); System.out.println("Marks : "
  • eElement .getElementsByTagName("marks") .item( 0 ) .getTextContent()); } } } catch (Exception e) { e.printStackTrace(); } } } This would produce the following result โˆ’ Root element :class

Current Element :student Student roll no : 393 First Name : dinkar Last Name : kad Nick Name : dinkar Marks : 85 Current Element :student Student roll no : 493 First Name : Vaneet Last Name : Gupta Nick Name : vinni Marks : 95

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("company"); doc.appendChild(rootElement); // staff elements Element staff = doc.createElement("Staff"); rootElement.appendChild(staff); // set attribute to staff element Attr attr = doc.createAttribute("id"); attr.setValue("1"); staff.setAttributeNode(attr); // shorten way // staff.setAttribute("id", "1"); // firstname elements Element firstname = doc.createElement("firstname"); firstname.appendChild(doc.createTextNode("yong")); staff.appendChild(firstname); // lastname elements Element lastname = doc.createElement("lastname"); lastname.appendChild(doc.createTextNode("mook kim")); staff.appendChild(lastname); // nickname elements Element nickname = doc.createElement("nickname"); nickname.appendChild(doc.createTextNode("mkyong")); staff.appendChild(nickname); // salary elements Element salary = doc.createElement("salary"); salary.appendChild(doc.createTextNode("100000")); staff.appendChild(salary); // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("C:\file.xml")); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result);

System.out.println("File saved!"); }