|
Introduction JDOM is a Java API independently developed by Sun Microsystems. It can handle XML data more simply than with conventional API. Its use is convenient for any Java developer and is based on XML API Sun. Sun Microsystems (Comment on the JSR-102 Approval Ballot) In general we tend to prefer to avoid adding new APIs to the Java platform which replicate the functionality of existing APIs. However JDOM does appear to be significantly easier to use than the earlier APIs, so we believe it will be a useful addition to the platform. You can download the binaries here. Objective of this article You learn in this article to manipulate given XML with Java and API JDOM. We will study the possibilities of this API through simple examples. We will learn to create a simple XML file, go to his tree, modify its content. 1. The origins of JDOM 1.1. Description SAX SAX is an acronym for Simple API for XML. Such events parser uses to steer the treatment of an XML file. An object (handler called in English) is to implement specific methods defined in an interface of the API to provide treatments to achieve: based on events, the parser calls these methods. To learn more about SAX, visit the official website. JDOM uses collections SAX parser for XML files. 1.2. Description DOM DOM is an acronym for Document Object Model. It is a W3C specification to propose an API that allows model, navigate and manipulate an XML document. The main role of DOM is to provide a memory representation of an XML document in the form of a tree of objects and to allow manipulation (tee, research and update).
Starting from this representation (the model), DOM proposes to browse the document, but also to be able to modify it. The latter is one of the most interesting aspect of DOM. DOM is set to be independent of the language in which it will be implemented. DOM is a specification that will be used, must be implemented by a third party. DOM is not specific to Java. The DOM parser for JAVA is the most widely Xerces you can find here. JDOM uses DOM to manipulate the elements of a specific Document Object Model (created by a manufacturer based on SAX). JDOM can therefore build documents, navigate their structure, in addition, modify or delete their content. 1.3. JDOM Why? A logical question that can arise at this stage of the article: But what JDOM brings us more? The simplicity! It is indeed very hard to develop complex applications around XML DOM, who remember it, has not been developed specifically for Java. Let's now look at all possibilities for JDOM through simple examples. 2. Creates an XML file with JDOM 2.1. Downloading and installing the API JDOM You need as a first step download the latest version of JDOM available at this address: http://www.jdom.org/dist/binary/. Then, to make available the file / build / jdom.jar, placing it in your classpath. 2.2. Create a simple tree The creation of an XML file from scratch is very simple. Suffice it to build each component can be added to each other in a logical manner. A node is an instance of org.jdom.Element. We therefore begin by creating a class JDOM1 who will take responsibility for creating the tree follows: XML file <personnes> <etudiant classe="P2"> <name> CynO </ name> <etudiant> <personnes> JDOM1.java import java.io. *; import org.jdom .*; import org.jdom.output .*; public class JDOM1 ( / / We'll start our tree by creating the root XML / / to be here "people". static Element root = new Element ( "people"); / / It creates a new document based on JDOM root that we have just created org.jdom.Document static document = new Document (root); public static void main (String [] args) ( / / It creates a new Element on the student and adds / / time qu'Element root Element student = new Element ( "student"); racine.addContent (student); / / It creates a new attribute class and it adds to student / / by using the setAttribute Attribute class = new Attribute ( "class", "P2"); etudiant.setAttribute (class); / / It creates a new Element name, he assigns the text / / and it adds time qu'Element of student Element name = new Element ( "name"); nom.setText ( "CynO"); etudiant.addContent (name); / / The following two methods will be defined later in the article display (); records ( "Exercice1.xml"); ) ) 2.3. Show and save its XML file JDOM1.java / / Add these two methods in our class JDOM1 static void display () ( try ( / / It uses a classic display with getPrettyFormat () XMLOutputter exit = new XMLOutputter (Format.getPrettyFormat ()); sortie.output (document System.out); ) catch (java.io.IOException e) () ) static void record (String file) ( try ( / / It uses a classic display with getPrettyFormat () XMLOutputter exit = new XMLOutputter (Format.getPrettyFormat ()); / / Note that simply create an instance of FileOutputStream / / argument with the file name to make the serialization. sortie.output (document, new FileOutputStream (file)); ) catch (java.io.IOException e) () ) After execution here is the result (display on the standard output and content of the file "Exercice1.xml"). Exercice1.xml <? xml version = "1.0" encoding = "UTF-8"?> <personnes> <etudiant classe="P2"> <name> CynO </ name> </ Student> </ persons> We will see in Part III how to work on an existing document, browse the tree and its filter elements. 3. Browse an XML file 3.1. Parser an XML file Parser an XML file is to transform an XML file into a tree JDOM. We will use it to the manufacturer SAXBuilder based, as its name suggests, the SAX API. First, create the following file in the directory containing your future class JDOM2: Exercice2.xml <? xml version = "1.0" encoding = "UTF-8"?> <persons> <Student class="P2"> <name> CynO </ name> <prenoms> <firstname> Nicolas </ first name> <firstname> Laurent </ first name> </ prenoms> </ Student> <Student class="P1"> <name> Superwoman </ name> </ Student> <Student class="P1"> <name> Don Corleone </ name> </ Student> </ persons> Our goal here is to display in a first time the names of all students. We will create for it a new class: JDOM2. JDOM2.java import java.io. *; import org.jdom .*; import org.jdom.input .*; import org.jdom.filter .*; import java.util.List; import java.util.Iterator; public class JDOM2 ( org.jdom.Document static document; Static Element root; public static void main (String [] args) ( / / It creates an instance of SAX Builder SAX Builder sxb = new SAX Builder (); try ( / / It creates a new document JDOM argument with the XML file / / The parsing is complete;) sxb.build document = (new File ( "Exercice2.xml")); ) catch (Exception e) () / / It initiates a new root element with the root element of the document. root = document.getRootElement (); / / Method defined in section 3.2. this article afficheALL (); ) ) 3.2. Browse a tree We will use this method in two classes belonging to the framework Collection (java.util package): java.util.List java.util.Iterator We will create a list based on nodes of our students tree then we will go through an iterator. JDOM2.java / / Add this method to class JDOM2 static void afficheALL () ( / / It creates a List containing all the nodes "student" of the Element root List listEtudiants = racine.getChildren (student); / / It creates an Iterator on our list Iterator i = listEtudiants.iterator (); while (i.hasNext ()) ( / / It recreates the current Element each turn loop in order to / / able to use methods of the Element as: / / select a node son, edit text, etc. ... Element current = (Element) i.next (); / / It displays the name of the current element System.out.println (courant.getChild ( "name"). GetText ()); ) ) A performance you should see CynO, Superwoman and Don Corleone.
3.3. Filter elements Our new target is to display the class of students whose first name is Lawrence and the name is CynO. The only filters that we have done for the moment were directly implementes in the methods we use. List listEtudiants = racine.getChildren ( "student") has enabled us to filter elements under root depending on their behalf. You may have noticed that anyway we had as students, the problem does not arise then;) The filters allow selection of items according to several criteria. We will therefore create a filter that will take into account that Elements that have: * A name element that must be value "CynO." * A prenoms element which must have at least one element in first_name whose value is "Lawrence". Once the filter created we can get a list containing the elements that meet these criteria. JDOM2.java / / Add this method to class JDOM2 / / Replace the line afficheALL (); by afficheFiltre (); static void afficheFiltre () ( / / It creates a new filter Filter filter = new Filter () ( / / It defined the properties of the filter through / / method matches public Boolean matches (Object ob) ( / / 1 age verification: it is verified that the objects / / to be screened are many Elements if (! (ob instance of Element)) (return false;) / / It then creates an element on which we will do / / audits. Element element = (Element) ob; / / It creates two variables that will allow us to verify / / conditions name and surname int verifNom = 0; int verifPrenom = 0; / / 2 th verification: it is verified that the name is "CynO" if (element.getChild ( "name"). getTextTrim (). equals ( "CynO")) ( verifNom = 1; ) / / 3 rd verification: it is verified that CynO has a name "Laurent" / / It starts with verifying that the person has a name, / / indeed our XML file has students without first name! Element prenoms element.getChild = ( "first names); if (prenoms == null) (return false;) / / There is a list with all first_name List listprenom = prenoms.getChildren ( "name"); / / Perform the audit browsing our list first_name / / (see: 3.1. Browse a tree) Iterator i = listprenom.iterator (); while (i.hasNext ()) ( Element current = (Element) i.next (); if (courant.getText (). equals ( "Lawrence")) ( verifPrenom = 1; ) ) / / If our conditions are met on returns true, false otherwise if (1 == verifNom & & verifPrenom == 1) ( return true; ) return false; ) ) / / End filter / / getContent will use our filter to create a list of students meeting / / our criteria. List racine.getContent result = (filter); / / On display at last attribute class of all elements of our list Iterator i = resultat.iterator (); while (i.hasNext ()) ( Element current = (Element) i.next (); System.out.println (courant.getAttributeValue ( "Class")); ) ) A performance you should see your screen P2. The power of this tool lies in its ability to be used at any time by any element of your tree. In our example, we used our filter JDOM as a search engine. And it is quite possible to create dynamic filters according to your needs. To learn more about the class Filter I invite you to come here. 4. Modifying a tree JDOM 4.1. Edit Elements | Name | Arguments of overweight | Description | | add Content | Collection, String or Content, i.e. a Element or whatever has to be content with a knot. | Add the contents of the argument at the end of the contents of a Element. You can specify an index to insert the desired position. | | clone | | Returns clone a perfect of the Element. | | clone Content | | As its name suggests it does not copy the contents. | | remove Attribute | Field name or attribute (String) | Removes attribute Element | | removeChild | behalf of the child node (String) | Remove the first child with this name. | | removeChildren | behalf of children knots (String) | Remove all children with this name. | | removeContent | Content, or filter Index | Removes an entire node informed argument or by its position. remove Content also accept filters, as get Content seen previously. | | setAttribute | Field or name of the attribute and its value (String, String) | This method allows both to create an attribute and change its value. | | setContent | Content | Replaces the contents of a Element.You can specify an index if you do not want to replace everything. | | setName | behalf of the New Element (String) | Change the name of the Element | | setText | New Text to insert (String) | Change the text content by the Element. TEXT <element> </ element> | | toString | | Returns a representation of the Element as a string. | For more details, I invite you to read the documentation for the class Element. Now see a small example of a change tree. You appear simplistic next to what we have done until now but it is precisely the aim: I want to show you that JDOM is simplicity above all! We will modify the content of our file Exemple2.xml removing all Element prenoms our tree. JDOM3.java / / Create a new class JDOM3 import java.io. *; import org.jdom .*; import org.jdom.input .*; import org.jdom.output .*; import java.util.List; import java.util.Iterator; public class JDom ( org.jdom.Document static document; Static Element root; public static void main (String [] args) ( try ( lireFichier ( "Exercise 2.xml"); supprElement ( "first names); enregistreFichier ( "Exercise 2.xml"); ) catch (Exception e) () ) / / Parse the file and initiates on the root / / our tree static void lireFichier (String file) throws Exception ( SAXBuilder sxb = new SAXBuilder (); sxb.build document = (new File (file)); root = document.getRootElement (); ) / / It makes changes to an Element static void supprElement (String element) ( / / In a first step on list all students List listEtudiant = racine.getChildren (student); Iterator i = listEtudiant.iterator (); / / On the list browsing through a iterator while (i.hasNext ()) ( Element current = (Element) i.next (); / / If the student has the Element in question is applied / / changes. if (courant.getChild (element)! = null) ( / / It removes the element in question courant.removeChild (element); / / On renames Element father knowing that tag does XML / / or spaces or special characters / / student modified "becomes" etudiant_modifie " courant.setName ( "etudiant_modifie"); ) ) ) / / On enregsitre our new tree in the file / / origin in a classical format. static void enregistreFichier (String file) throws Exception ( XMLOutputter exit = new XMLOutputter (Format.getPrettyFormat ()); sortie.output (document, new FileOutputStream (file)); ) ) Here are the contents of the file "Exemple2.xml" after execution. Exemple2.xml <? xml version = "1.0" encoding = "UTF-8"?> <persons> <Student_modifie class="P2"> <name> CynO </ name> </ Student_modifie> <Student class="P1"> <name> Superwoman </ name> </ Student> <Student class="P1"> <name> Don Corleone </ name> </ Student> </ persons> 4.2. Moving from a DOM JDOM and vice versa It happens sometimes you have to work on a document DOM. We'll see how to transform a document into a DOM document JDOM and vis versa. Here is a small method that receives a document DOM argument and returns a document JDOM. / / To be compiled this function requires the following import / / which contains the class DOMBuilder import org.jdom.input .*; org.jdom.Document DOMtoJDOM (org.w3c.dom.Document documentDOM) throws Exception ( / / It uses the class DOMBuilder for this transformation DOMBuilder builder = new DOMBuilder (); org.jdom.Document documentJDOM = builder. build (documentDOM); documentJDOM return; ) And now, here is the reverse function which receives a document JDOM argument and returns a DOM document. You will notice the similarity with the previous function. / / To be compiled this function requires the following import / / which contains the class DOMOutputter import org.jdom.output .*; org.w3c.dom.Document DOMtoJDOM (org.jdom.Document documentJDOM) throws Exception ( / / It uses the class DOMOutputter for this transformation DOMOutputter domOutputter = new DOMOutputter (); org.w3c.dom.Document documentDOM = domOutputter.output (documentJDOM); documentDOM return; ) 4.3. JDOM and XSLT Thanks to the API JAXP TraX and it is very easy to make XSLT transformation on a document JDOM. In the following example we'll create a method that takes as input a document JDOM and the name of a file XSL and creates an output XML file transformed. / / To be compiled this function requires imports following import java.io. *; / / JDOM import org.jdom.transform .*; import org.jdom.output .*; / / TrAX import javax.xml.transform .*; import javax.xml.transform.stream.StreamSource; void outputXSLT (org.jdom.Document documentJDOMEntree, String fichierXSL) ( / / Document JDOMResult result of the transformation TraX JDOMResult documentJDOMSortie = new JDOMResult (); / / Document JDOM after processing org.jdom.Document result = null; try ( / / It defines a turn with the source XSL / / which will allow the transformation TransformerFactory factory = TransformerFactory.newInstance (); Transformer transform = factory.newTransformer (new StreamSource (fichierXSL)); / / It transforms the document JDOMEntree through our turn. / / The méthoded transform () takes the argument document entree associated with transforming / / and a document JDOMResult result of the transformation TraX transformer.transform (new org.jdom.transform.JDOMSource (documentJDOMEntree), documentJDOMSortie); / / To retrieve the document JDOM from this transformation / / you must use the method getDocument () documentJDOMSortie.getDocument result = (); / / It creates a file xml corresponding to the result XMLOutputter outputter = new XMLOutputter (Format.getPrettyFormat ()); outputter.output (result, new FileOutputStream ( "resultat.xml")); ) catch (Exception e) () ) Conclusion You have now realized the usefulness of JDOM in data processing XML with Java. However, this API is still very young and being improved.
|