There are many ways to store data. You can use a Text File or Database or even XML File.
It is very important to use xml to store and retreive from because it is very simple , easy and designed to be self-descriptive.
Extensible Markub Language (XML) is a markup language that defines some set of rules for encoding in a simple and readable format. It was disigned to carry data and not to display data.So, As we said XML is created to store, structure and transport data
Using the code
the first step we need to do is to add an External Jar Library called "Jdom-2.0.5.jar" and add the xml file that you want to add.In our case our file called "TauxChomage.xml". click right on the project and choose properties as shown :
the xml file contains the rate of jobless in different countries. For example in Canada the rate jobless in 2005 is 7.0 for men and 9.5 for women as shown below:
The question here : how we can retreive these data from this xml file to manipulate it ?
we want to display just the average rate in a specific datefor each country.we want to create a method in which we will make our process starting by reading our file in an element called "chommage"
public static void readXmlFile() throws JDOMException, IOException
Element Chommage = ((Document)(new SAXBuilder()).build(new File ("TauxChomage.xml"))).getRootElement();
In order to read all countries we need to use this piece of code:
List listpays = Chommage.getChildren("pays");
After that we need to reach all of the racine to extract the name and the rate value and to store the Countries rate in three memory cases that represents a specific date
Iterator i = listpays.iterator();
Element courant = (Element)i.next();
List listTaux = courant.getChildren("taux");
Iterator j = listTaux.iterator();
Element tauxElem= (Element)j.next();
Now, we can manipulate the result and display it easily:
System.out.print(" | Annee 2006 : "+t2/2);
System.out.println(" | Annee 2007 : "+t3/2);
System.out.println("Le taux de chommage globale de L'annee 2005 "+somme1/24);
System.out.println("Le taux de chommage globale de L'annee 2006 "+somme2/24);
System.out.println("Le taux de chommage globale de L'annee 2007 "+somme3/24);
Now, when we compile the program, we see this result:
Well done! Working with Xml is very easy as we saw together in this tip. Download the code source and you can understand more with it.