SlideShare a Scribd company logo
DOM
How to print the xml
elements(nodes) as ordered list
Index.xml
<?xml version="1.0"?>
<class>
<student rollno="393">
<firstname>dinkar</firstname>
<lastname>kad</lastname>
<nickname>dinkar</nickname>
<marks>85</marks>
</student>
<student rollno="493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>vinni</nickname>
<marks>95</marks>
</student>
<student rollno="593">
<firstname>jasvir</firstname>
<lastname>singn</lastname>
<nickname>jazz</nickname>
<marks>90</marks>
</student>
</class>
DomParserDemo.java
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class DomParserDemo
{
public static void main(String[] args){
try {
inputFile = new File("input.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
The normalize() method merges adjacent text() nodes and removes empty ones in the
whole document.
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
//returns a list of subelements of specified name
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)// check for 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(); //useful tool for diagnosing an Exception
}
}
}
Output will be
Root element :class
----------------------------
Current Element :student
Student roll no : 393
First Name : dinkar
Last Name : kad
Nick Name : dinkarMarks : 85
Current Element :student
Student roll no : 493
First Name : Vaneet
Last Name : Gupta
Nick Name : vinniMarks : 95
Current Element :student
Student roll no : 593
First Name : jasvir
Last Name : singh
Nick Name : jazz
Marks : 90
How to create the xml document
import javax.xml.parsers.*;
import javax.xml.transform.*;
import org.w3c.dom.*;
import java.io.*;
public class CreateXmlFileDemo
{
public static void main(String argv[])
{ try
{
DocumentBuilderFactory dbFactory =DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.newDocument();
// root element
Element rootElement = doc.createElement("cars");
doc.appendChild(rootElement); // supercars element
Element supercar = doc.createElement("supercars");
rootElement.appendChild(supercar); // setting attribute to element
Attr attr = doc.createAttribute("company");
attr.setValue("Ferrari");
supercar.setAttributeNode(attr); // carname element
Element carname = doc.createElement("carname");
Attr attrType = doc.createAttribute("type");
attrType.setValue("formula one");
carname.setAttributeNode(attrType);
carname.appendChild( doc.createTextNode("Ferrari 101"));
supercar.appendChild(carname);
Element carname1 = doc.createElement("carname");
Attr attrType1 = doc.createAttribute("type");
attrType1.setValue("sports");
carname1.setAttributeNode(attrType1);
carname1.appendChild(doc.createTextNode("Ferrari 202"));
supercar.appendChild(carname1);
// 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:cars.xml"));
transformer.transform(source, result); // Output to console for testing
StreamResult consoleResult =new StreamResult(System.out);
transformer.transform(source, consoleResult);
}
catch (Exception e)
{
e.printStackTrace();
} }}
OUTPUT will be
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<cars>
<supercars company="Ferrari">
<carname type="formula one">Ferrari 101</carname>
<carname type="sports">Ferrari 202</carname>
</supercars>
</cars>
(you will have cars.xml created in C:>
How to modify the xmldocument
Original XML file(input.xml)
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<cars>
<supercars company="Ferrari">
<carname type="formula one">Ferrari 101</carname>
<carname type="sports">Ferrari 202</carname>
</supercars>
<luxurycars company="Benteley">
<carname>Benteley 1</carname>
<carname>Benteley 2</carname>
<carname>Benteley 3</carname>
</luxurycars>
</cars>
import java.io.File;
import javax.xml.parsers.*;I
import javax.xml.transform.*;
import org.w3c.dom.*;
public class ModifyXmlFileDemo
{ public static void main(String argv[])
{ try {
File inputFile = new File("input.xml");
DocumentBuilderFactory docFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(inputFile);
Node cars = doc.getFirstChild();
Node supercar = doc.getElementsByTagName("supercars").item(0); //
update supercar attribute
NamedNodeMap attr = supercar.getAttributes();
Node nodeAttr = attr.getNamedItem("company");
nodeAttr.setTextContent("Lamborigini"); // loop the supercar child node
NodeList list = supercar.getChildNodes();
for (int temp = 0; temp < list.getLength(); temp++)
{
Node node = list.item(temp);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) node;
if ("carname".equals(eElement.getNodeName()))
{
if("Ferrari 101".equals(eElement.getTextContent()))
{
eElement.setTextContent("Lamborigini 001");
}
if("Ferrari 202".equals(eElement.getTextContent()))
eElement.setTextContent("Lamborigini 002");
}
}
}
NodeList childNodes = cars.getChildNodes();
for(int count = 0; count < childNodes.getLength(); count++)
{
Node node = childNodes.item(count);
if("luxurycars".equals(node.getNodeName()))
cars.removeChild(node);
} // write the content on console
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
System.out.println("-----------Modified File-----------");
StreamResult consoleResult = new StreamResult(System.out);
transformer.transform(source, consoleResult);
}
catch (Exception e)
{ e.printStackTrace();
} }}
Output will be
-----------Modified File-----------
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<cars>
<supercars company="Lamborigini">
<carname type="formula one">Lamborigini 001</carname>
<carname type="sports">Lamborigini 002</carname>
</supercars>
</cars>

More Related Content

PDF
jQuery: out with the old, in with the new
PPTX
Power shell voor developers
KEY
CoffeeScript - A Rubyist's Love Affair
DOCX
logic321
PDF
Command Bus To Awesome Town
PDF
Models and Service Layers, Hemoglobin and Hobgoblins
PDF
50 Laravel Tricks in 50 Minutes
PDF
Things I Believe Now That I'm Old
jQuery: out with the old, in with the new
Power shell voor developers
CoffeeScript - A Rubyist's Love Affair
logic321
Command Bus To Awesome Town
Models and Service Layers, Hemoglobin and Hobgoblins
50 Laravel Tricks in 50 Minutes
Things I Believe Now That I'm Old

What's hot (20)

PPTX
Views notwithstanding
PDF
Introducción rápida a SQL
KEY
Symfony2 Building on Alpha / Beta technology
PDF
Shortcodes In-Depth
PDF
Python Ireland Nov 2010 Talk: Unit Testing
PDF
Make your own wp cli command in 10min
PDF
PHP tips and tricks
PDF
November Camp - Spec BDD with PHPSpec 2
PPT
My sql presentation
PDF
ECMAScript2015
PDF
ATK 'Beyond The Pizza Guides'
PDF
Bag Of Tricks From Iusethis
PDF
PofEAA and SQLAlchemy
KEY
Why ruby
KEY
Ruby/Rails
PDF
A Tour to MySQL Commands
PPTX
Building secured wordpress themes and plugins
PDF
PHP 5.3 and Lithium: the most rad php framework
PDF
Wordpress plugin development from Scratch
PDF
The Zen of Lithium
Views notwithstanding
Introducción rápida a SQL
Symfony2 Building on Alpha / Beta technology
Shortcodes In-Depth
Python Ireland Nov 2010 Talk: Unit Testing
Make your own wp cli command in 10min
PHP tips and tricks
November Camp - Spec BDD with PHPSpec 2
My sql presentation
ECMAScript2015
ATK 'Beyond The Pizza Guides'
Bag Of Tricks From Iusethis
PofEAA and SQLAlchemy
Why ruby
Ruby/Rails
A Tour to MySQL Commands
Building secured wordpress themes and plugins
PHP 5.3 and Lithium: the most rad php framework
Wordpress plugin development from Scratch
The Zen of Lithium
Ad

Similar to DOM PARSER (20)

PPT
SAX PARSER
PPTX
java API for XML DOM
PPTX
06 xml processing-in-.net
PDF
Advanced Web Programming Chapter 12
PDF
Building XML Based Applications
PPTX
PPTX
Unit 2
PDF
25dom
PPTX
buildingxmlbasedapplications-180322042009.pptx
PDF
Parsing XML Data
PDF
Processing XML
PPTX
PPT
XML and XPath details
PDF
IT6801-Service Oriented Architecture-Unit-2-notes
PPT
Processing XML with Java
PPTX
Xml writers
PDF
Tool Development 04 - XML
PPT
Xml Java
PDF
Data formats
PPTX
Unit iv xml dom
SAX PARSER
java API for XML DOM
06 xml processing-in-.net
Advanced Web Programming Chapter 12
Building XML Based Applications
Unit 2
25dom
buildingxmlbasedapplications-180322042009.pptx
Parsing XML Data
Processing XML
XML and XPath details
IT6801-Service Oriented Architecture-Unit-2-notes
Processing XML with Java
Xml writers
Tool Development 04 - XML
Xml Java
Data formats
Unit iv xml dom
Ad

Recently uploaded (20)

PDF
Influence of Green Infrastructure on Residents’ Endorsement of the New Ecolog...
PPTX
"Array and Linked List in Data Structures with Types, Operations, Implementat...
PPTX
Amdahl’s law is explained in the above power point presentations
PDF
August 2025 - Top 10 Read Articles in Network Security & Its Applications
PDF
Categorization of Factors Affecting Classification Algorithms Selection
PDF
Accra-Kumasi Expressway - Prefeasibility Report Volume 1 of 7.11.2018.pdf
PPTX
Software Engineering and software moduleing
PDF
Abrasive, erosive and cavitation wear.pdf
PDF
EXPLORING LEARNING ENGAGEMENT FACTORS INFLUENCING BEHAVIORAL, COGNITIVE, AND ...
PDF
ChapteR012372321DFGDSFGDFGDFSGDFGDFGDFGSDFGDFGFD
PPTX
Fundamentals of safety and accident prevention -final (1).pptx
PDF
Human-AI Collaboration: Balancing Agentic AI and Autonomy in Hybrid Systems
PPTX
Fundamentals of Mechanical Engineering.pptx
PPTX
AUTOMOTIVE ENGINE MANAGEMENT (MECHATRONICS).pptx
PPTX
Feature types and data preprocessing steps
PPTX
introduction to high performance computing
PDF
UNIT no 1 INTRODUCTION TO DBMS NOTES.pdf
PPTX
Current and future trends in Computer Vision.pptx
PPTX
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life App...
PPT
Total quality management ppt for engineering students
Influence of Green Infrastructure on Residents’ Endorsement of the New Ecolog...
"Array and Linked List in Data Structures with Types, Operations, Implementat...
Amdahl’s law is explained in the above power point presentations
August 2025 - Top 10 Read Articles in Network Security & Its Applications
Categorization of Factors Affecting Classification Algorithms Selection
Accra-Kumasi Expressway - Prefeasibility Report Volume 1 of 7.11.2018.pdf
Software Engineering and software moduleing
Abrasive, erosive and cavitation wear.pdf
EXPLORING LEARNING ENGAGEMENT FACTORS INFLUENCING BEHAVIORAL, COGNITIVE, AND ...
ChapteR012372321DFGDSFGDFGDFSGDFGDFGDFGSDFGDFGFD
Fundamentals of safety and accident prevention -final (1).pptx
Human-AI Collaboration: Balancing Agentic AI and Autonomy in Hybrid Systems
Fundamentals of Mechanical Engineering.pptx
AUTOMOTIVE ENGINE MANAGEMENT (MECHATRONICS).pptx
Feature types and data preprocessing steps
introduction to high performance computing
UNIT no 1 INTRODUCTION TO DBMS NOTES.pdf
Current and future trends in Computer Vision.pptx
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life App...
Total quality management ppt for engineering students

DOM PARSER

  • 1. DOM
  • 2. How to print the xml elements(nodes) as ordered list
  • 3. Index.xml <?xml version="1.0"?> <class> <student rollno="393"> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>85</marks> </student> <student rollno="493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>95</marks> </student> <student rollno="593"> <firstname>jasvir</firstname> <lastname>singn</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> </class>
  • 4. DomParserDemo.java import java.io.*; import javax.xml.parsers.*; import org.w3c.dom.*; public class DomParserDemo { public static void main(String[] args){ try { inputFile = new File("input.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(inputFile); doc.getDocumentElement().normalize(); The normalize() method merges adjacent text() nodes and removes empty ones in the whole document. System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); //returns a list of subelements of specified name NodeList nList = doc.getElementsByTagName("student"); System.out.println("----------------------------");
  • 5. 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)// check for element node { Element eElement = (Element) nNode; System.out.println("Student roll no : " + eElement.getAttribute("rollno"));
  • 6. 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(); //useful tool for diagnosing an Exception } } }
  • 7. Output will be Root element :class ---------------------------- Current Element :student Student roll no : 393 First Name : dinkar Last Name : kad Nick Name : dinkarMarks : 85 Current Element :student Student roll no : 493 First Name : Vaneet Last Name : Gupta Nick Name : vinniMarks : 95 Current Element :student Student roll no : 593 First Name : jasvir Last Name : singh Nick Name : jazz Marks : 90
  • 8. How to create the xml document
  • 9. import javax.xml.parsers.*; import javax.xml.transform.*; import org.w3c.dom.*; import java.io.*; public class CreateXmlFileDemo { public static void main(String argv[]) { try { DocumentBuilderFactory dbFactory =DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.newDocument(); // root element Element rootElement = doc.createElement("cars"); doc.appendChild(rootElement); // supercars element Element supercar = doc.createElement("supercars"); rootElement.appendChild(supercar); // setting attribute to element Attr attr = doc.createAttribute("company"); attr.setValue("Ferrari");
  • 10. supercar.setAttributeNode(attr); // carname element Element carname = doc.createElement("carname"); Attr attrType = doc.createAttribute("type"); attrType.setValue("formula one"); carname.setAttributeNode(attrType); carname.appendChild( doc.createTextNode("Ferrari 101")); supercar.appendChild(carname); Element carname1 = doc.createElement("carname"); Attr attrType1 = doc.createAttribute("type"); attrType1.setValue("sports"); carname1.setAttributeNode(attrType1); carname1.appendChild(doc.createTextNode("Ferrari 202")); supercar.appendChild(carname1);
  • 11. // 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:cars.xml")); transformer.transform(source, result); // Output to console for testing StreamResult consoleResult =new StreamResult(System.out); transformer.transform(source, consoleResult); } catch (Exception e) { e.printStackTrace(); } }}
  • 12. OUTPUT will be <?xml version="1.0" encoding="UTF-8" standalone="no"?> <cars> <supercars company="Ferrari"> <carname type="formula one">Ferrari 101</carname> <carname type="sports">Ferrari 202</carname> </supercars> </cars> (you will have cars.xml created in C:>
  • 13. How to modify the xmldocument
  • 14. Original XML file(input.xml) <?xml version="1.0" encoding="UTF-8" standalone="no"?> <cars> <supercars company="Ferrari"> <carname type="formula one">Ferrari 101</carname> <carname type="sports">Ferrari 202</carname> </supercars> <luxurycars company="Benteley"> <carname>Benteley 1</carname> <carname>Benteley 2</carname> <carname>Benteley 3</carname> </luxurycars> </cars>
  • 15. import java.io.File; import javax.xml.parsers.*;I import javax.xml.transform.*; import org.w3c.dom.*; public class ModifyXmlFileDemo { public static void main(String argv[]) { try { File inputFile = new File("input.xml"); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(inputFile); Node cars = doc.getFirstChild(); Node supercar = doc.getElementsByTagName("supercars").item(0); // update supercar attribute NamedNodeMap attr = supercar.getAttributes(); Node nodeAttr = attr.getNamedItem("company"); nodeAttr.setTextContent("Lamborigini"); // loop the supercar child node NodeList list = supercar.getChildNodes();
  • 16. for (int temp = 0; temp < list.getLength(); temp++) { Node node = list.item(temp); if (node.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) node; if ("carname".equals(eElement.getNodeName())) { if("Ferrari 101".equals(eElement.getTextContent())) { eElement.setTextContent("Lamborigini 001"); } if("Ferrari 202".equals(eElement.getTextContent())) eElement.setTextContent("Lamborigini 002"); } } } NodeList childNodes = cars.getChildNodes(); for(int count = 0; count < childNodes.getLength(); count++) { Node node = childNodes.item(count); if("luxurycars".equals(node.getNodeName())) cars.removeChild(node); } // write the content on console
  • 17. TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); System.out.println("-----------Modified File-----------"); StreamResult consoleResult = new StreamResult(System.out); transformer.transform(source, consoleResult); } catch (Exception e) { e.printStackTrace(); } }}
  • 18. Output will be -----------Modified File----------- <?xml version="1.0" encoding="UTF-8" standalone="no"?> <cars> <supercars company="Lamborigini"> <carname type="formula one">Lamborigini 001</carname> <carname type="sports">Lamborigini 002</carname> </supercars> </cars>