How to work with the DOM & XML files using JAVA!

Welcome gang in another article ! today I am going to explain to you the basics of the DOM (document object model) using JAVA!
First let me explain to you what does DOM mean :
Dom: The Document Object Model (DOM) is an application programming interface (API) for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated. In the DOM specification, the term “document” is used in the broad sense — increasingly, XML is being used as a way of representing many different kinds of information that may be stored in diverse systems, and much of this would traditionally be seen as data rather than as documents. Nevertheless, XML presents this data as documents, and the DOM may be used to manage this data.
With the Document Object Model, programmers can build documents, navigate their structure, and add, modify, or delete elements and content. Anything found in an HTML or XML document can be accessed, changed, deleted, or added using the Document Object Model.
And for not making this article boring, I will show you exactly how to use DOM with XML files using JAVA:
first Let me produce to you the xml file which we gonna work with :
<?xml version=”1.0" encoding=”UTF-8" standalone=”yes” ?>
<filmographie>
<film type = “action”>
<nom>Hannibal</nom>
<type>action</type>
<story>
<first>Dr Hannibal Lecter, who was arrested for cannibalism, now lives at an unknown location under a new identity. One of the victims, Mason Verger, makes an elaborate plan to find him and avenge himself.</first>
</story>
<story>
<first>action story about a serial killer</first>
</story>
</film>
</filmographie>
Step 1 : create an instance of “DocumentBuilderFactory” */
DocumentBuilderFactory: is a class responsible of building and handling a document in our case is the xml doc;
We can do that by :
final DocumentBuilder builder = factory.newDocumentBuilder();
* step 2 : create a parser:
now let’s create our parser to parse our xml file:
final DocumentBuilder builder = factory.newDocumentBuilder();
* step 3 : create a document that will contains our xml File
now we can handle our xml file with the builder var (parser) and we can parse the file content and store it on a variable called document which is an
instance of Document class:
final Document document= builder.parse(new File(“repertoire.xml”));
now we are working with xml file that’s is linked with our document var with the parser ! got me ? it’s like the parser is a bridge between the java and the xmlxml
file **** builder(parser) **** xml File
* step 4 : get the root element
Now we can surf in the xml file easily !
We can get the root Node by :
final Element root = document.getDocumentElement() ;
and to get the name we just need :
System.out.println(root.getNodeName());
Also we can every information about the xml file by :
document.getXmlVersion(): get the version;
document.getXmlStandalone(): get the standalone;
* step 5 : get the film node
Move on to the content of the nodes now :
As we know the root element contains:
3 nodes : name — type — story
So we need to work with the root as NodeList and we need to get the nodes of the root one by one,
final NodeList rootNoeuds = root.getChildNodes();
the best solution here is a loop right ?
now based on the number of the items in the root node we make our for loop
final int nbRootNoeuds = rootNoeuds.getLength();
after that :
for (int i = 0; i< nbRootNoeuds; i++)
{
if(racineNoeuds.item(i).getNodeType() == Node.ELEMENT_NODE){
now we are going to store every root item( film) and handle it before we pass to the next item which is (film) too !
final Element film = (Element) rootNoeuds.item(i);
System.out.println(“\n*************film************”); System.out.println(“type : “ + film.getAttribute(“type”));
film.getAttribute : is used to get the attribute of the
We can get them by a loop which every film node is a called an item :
Se first we get the first node( start with 0) :
* step 6 : get the name and the type of the film
First we select the name node and type node!
final Element nom = (Element) film.getElementsByTagName(“nom”).item(i);
final Element type = (Element) film.getElementsByTagName(“type”).item(i);
after that we log them out :
System.out.println(“nom : “ + nom.getTextContent());
System.out.println(“type : “ + type.getTextContent());
* step 7 : get the story of the film
Last step is to handle the stories which is a node contains nodes it’s a node List:
We select them first :
final NodeList stories = film.getElementsByTagName(“story”);
final int nbStories = stories.getLength();
and again we are going to use the for loop to log them out all :
for(int j = 0; j<nbStories; j++)
{
final Element story = (Element) stories.item(j);
//Affichage du téléphone
System.out.println(“story : “ + j + “ “ + story.getTextContent()); }
}
now for the full code :
package exercice1;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class main
{
public static void main(final String[] args)
{
/*
* Etape 1 : récupération d’une instance de la classe “DocumentBuilderFactory” */
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try
{
/*
* Etape 2 : création d’un parseur
*/
final DocumentBuilder builder = factory.newDocumentBuilder(); /*
* Etape 3 : création d’un Document
*/
final Document document= builder.parse(new File(“repertoire.xml”));
//Affichage du prologue
System.out.println(“*************PROLOGUE************”); System.out.println(“version : “ + document.getXmlVersion());
System.out.println(“encodage : “ + document.getXmlEncoding()); System.out.println(“standalone : “ + document.getXmlStandalone()); /*
* Etape 4 : récupération de l’Element racine
*/
final Element racine = document.getDocumentElement();
//Affichage de l’élément racine
System.out.println(“\n*************RACINE************”); System.out.println(racine.getNodeName());
/*
* Etape 5 : récupération des personnes
*/
final NodeList racineNoeuds = racine.getChildNodes();
final int nbRacineNoeuds = racineNoeuds.getLength();
for (int i = 0; i<nbRacineNoeuds; i++)
{
if(racineNoeuds.item(i).getNodeType() == Node.ELEMENT_NODE) {
final Element film = (Element) racineNoeuds.item(i);
//Affichage d’une personne
System.out.println(“\n*************film************”); System.out.println(“type : “ + film.getAttribute(“type”));
/*
* Etape 6 : récupération du nom et du prénom
*/
final Element nom = (Element) film.getElementsByTagName(“nom”).item(0); final Element type = (Element) film.getElementsByTagName(“type”).item(0);
//Affichage du nom et du prénom
System.out.println(“nom : “ + nom.getTextContent());
System.out.println(“type : “ + type.getTextContent());
/*
* Etape 7 : récupération des numéros de téléphone
*/
final NodeList stories = film.getElementsByTagName(“story”);
final int nbStories = stories.getLength();
for(int j = 0; j<nbStories; j++)
{
final Element story = (Element) stories.item(j);
//Affichage du téléphone
System.out.println(story.getAttribute(“type”) + “ : “ + story.getTextContent()); }
}
}
}
catch (final ParserConfigurationException e)
{
e.printStackTrace();
}
catch (final SAXException e)
{
e.printStackTrace();
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
Hope you guys enjoy this article and let’s meet in the very soon with another information !
Coding is an art !