java.net member

Rechercher dans ce site

Les opérations XML en Java partie 2

>> 13 June 2010

[FR]


Ce tutoriel utilise uniquement le JDK. Pas besoin d'autres installations

Question de validation
Pour parcourir un document et extraire ses composants, deux options sont disponibles, verifier la structure du document, ou bien être obligé de vérifier les éléments retournés et détecter des erreurs !!!

DTD règles de base
Il est possible de fournir les règles de vérification d'un document XML en utilisant "des grammaires" , une DTD par exemple insérée au sein même du document, ou à partir d'un fichier .dtd

Par exemple pour un fichier de templates Eclipse, on met la déclartion de DTD directement après l'en-tête " xml "

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE templates [
   <!ELEMENT templates (template)+>
   ...
]>

  • Le type de document dans la DTD doit avoir le nom de la racine (root)
  • Les élément contenus dans la racine sont spécifiés en utilisant des expressions régulières
  • Pour un fichier de templates, la racine est " templates " et contient un ou plusieur élément enfants " template " (sans s)

  • Chaque élément enfant contient un texte (le corps du template)

<!ELEMENT template (#PCDATA) >

  • Les templates (élément enfant) ont des attributs.

<!ATTLIST template context (javadoc|java) "java">

Un exemple de DTD (ce n'est pas une DTD réelle)

<!DOCTYPE templates [
   <!ELEMENT templates (template)+>
   <!ELEMENT template (#PCDATA) >
   <!ATTLIST template autoinsert (true|false) #REQUIRED>
 
   <!ATTLIST template context (javadoc|java) #REQUIRED>
   <!ATTLIST template deleted (true|false) #REQUIRED>
 
   <!ATTLIST template description CDATA #REQUIRED>
   <!ATTLIST template enabled  (true|false) #REQUIRED>
   <!ATTLIST template id ID #IMPLIED>
   <!ATTLIST template name CDATA #REQUIRED>
 
]>

Validation en utilisant Java
Pour valider un document en Java, il faut fournir une DTD du document et appeler la méthode setValidating(true) d'un objet DocumentBuilderFactory

Important :
Appelez la méthode setIgnoringElementContentWhitespace(true), pour éviter des exceptions. Cette méthode ignore les éspaces entre les éléments.

Exemple :
try {
  
    DocumentBuilderFactory     documentBuilderFactory=DocumentBuilderFactory.newInstance();
  
  
    documentBuilderFactory.setValidating(true);
    documentBuilderFactory.setIgnoringElementContentWhitespace(true);
  
      ...
      ..
     }
catch(Exception e)
{
...
}

Read more...

XML Parsing in Java part 2

Using only the JDK (nothing to install)

Validating or not validating?

For parsing XML it's not at all necessary to validating document before. But what if your document does not have the structure you think it has? Although it's possible to check all what you get as elements or child. It's simpler to provide a DTD of the document and let Java check  the correct structure of the document.

DTD basic rules

Supplying a DTD, there are some methods to provide a DTD for instance :

You can include a DTD in an XML document
or
Use SYSTEM and give the path to an external file

For our example of Eclipse Template file, put the DTD directly after the xml declaration

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE templates [
   <!ELEMENT templates (template)+>
   ...
]>

  • The document type must match the name of the root element (templates)
  • Elements are specified using regular expression. Here for instance "templates" contains 1 or more template.

  • Each template (Child element) contains "Text"

<!ELEMENT template (#PCDATA) >

  • And attributes like context :

<!ATTLIST template context (javadoc|java) "java">

Example of a DTD (This is just an example of a DTD for templates in Eclipse)
<!DOCTYPE templates [
   <!ELEMENT templates (template)+>
   <!ELEMENT template (#PCDATA) >
   <!ATTLIST template autoinsert (true|false) #REQUIRED>
 
   <!ATTLIST template context (javadoc|java) #REQUIRED>
   <!ATTLIST template deleted (true|false) #REQUIRED>
 
   <!ATTLIST template description CDATA #REQUIRED>
   <!ATTLIST template enabled  (true|false) #REQUIRED>
   <!ATTLIST template id ID #IMPLIED>
   <!ATTLIST template name CDATA #REQUIRED>
 
]>

What a bout Java?
When you provide a DTD for your XML file call the method setValidating(true)
On an object of DocumentBuilderFactory

Note:
One more step. Call also setIgnoringElementContentWhitespace(true), if you don't want to get exceptions. This way the parser stops to report white-spaces between elements.

Example :
try {
  
    DocumentBuilderFactory     documentBuilderFactory=DocumentBuilderFactory.newInstance();
  
  
    documentBuilderFactory.setValidating(true);
    documentBuilderFactory.setIgnoringElementContentWhitespace(true);
  
      ...
      ..
     }
catch(Exception e)
{
...
}

Read more...

Les opérations XML en Java partie 1

>> 04 June 2010

Ce tutoriel utilise le parser fourni avec le JDK. L'installation d'un autre parser n'est pas nécessaire.

Comment utiliser java pour parcourir un document XML et extraire ses éléments. Comment extraire des attributs, le texte d'un élément, etc.

La structure des documents XML
Un document XML est composé principalement d'éléments et texte.


Les composants essentiels d'un document
1.Header
2.Elément racine
3.Eléments enfants

L'élément racine, peut avoir un ou plusieurs éléments (enfants). Un élément peut contenir un élément enfant ou un texte ou les deux. Un élément peut aussi avoir des attributs

XML Header
<?xml version="1,0" encoding="UTF-8"?>

Prenons comme  example un template Eclipse
L'élément racine ici est <templates> (avec s). Un élément enfant est entre <template> et </template>. Un <template> a des attributs (nom/valeur). Le texte pour un template est son contenu.


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<templates>
    <template autoinsert="true" context="catchblock_context" deleted="false"     description="Code in new catch blocks" enabled="true"     id="org.eclipse.jdt.ui.text.codetemplates.catchblock" name="catchblock">
    // ${todo} Auto-generated catch block
    ${exception_var}.printStackTrace();</template>
</templates>

Le parser
Un parser est un programme servant à lire, vérifier et extraire les éléments d'un document XML

Les parsers de Java
DOM parser -> lit un document et forme un arbre de ses éléments
SAX parser -> lance des événements Java au passage des éléments XML

Comment ça marche ?
1-Appelez newDocumentBuilder() sur un objet DocumentBuilderFactory pour avoir
  un objet DocumentBuilder.
 
DocumentBuilderFactory     documentBuilderFactory=DocumentBuilderFactory.newInstance();
  DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder();

2-Passez un objet File (On peut aussi utiliser un URL) à la méthode parse. Cette méthode retourne une réference de Document (Le document XML)

  File file=new File("fileName");
  Document document=documentBuilder.parse(file);

3-Avec la référence Document on peut parcourir les éléments XML
  -Elément racine
  -Elément enfants
  -Contenu et attributs



4-(Racine ou root)
  Element root=document.getDocumentElement();

5-Elément enfants
  //NodeList est une collection de Nodes
    NodeList children = root.getChildNodes();
    for (int i = 0; i < children.getLength(); i++)
    {
      
    Node child = children.item(i);
    //get rid of white spaces
    if(child instanceof Element)
     {
        ...
        ...
     }//~if a child is element
    }//~children

6-Et les attributs
  NamedNodeMap attributes=child.getAttributes();
          
  for(int j=0;j<attributes.getLength();j++)
    {
    Node attribute=attributes.item(j);
    if(!(attribute instanceof Node) )
        continue;
    String attributeName=attribute.getNodeName();
    String attributeValue=attribute.getNodeValue();
              
    }//~attributes

7-Beaucoup d'opérations sont disponibles sur des éléments XML
 Par exemple :
  - Obtenir le nom d'un élément : getTagName()
  - L'attribut d'un node en passant son nom : getAttributeNode(String name)
  - Supprimer un attribut en donnant son nom : removeAttribute(String name)
  Consultez Javadoc

Un petit programme
package com.java_javafx.ka;

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.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;

/*
@author Kaesar ALNIJRES
*/

public class Test {
public void test()
{
//parse a file, get root element, children elements and their attributes

try {
    //prepare to read the xml document, by getting a DocumentBuilder
    DocumentBuilderFactory     documentBuilderFactory=DocumentBuilderFactory.newInstance();
    DocumentBuilder      documentBuilder=documentBuilderFactory.newDocumentBuilder();
    File file=new File("put_a_path_to_xml_file");
    Document document=documentBuilder.parse(file);
  
    //get the root element
    Element root=document.getDocumentElement();
  
    //get the root's name
    String string2=root.getTagName();
  
    System.out.println("root "+string2);
  
    //get a list of children
    NodeList children = root.getChildNodes();
    for (int i = 0; i < children.getLength(); i++)
    {
      
        Node child = children.item(i);
        //no white spaces
        if(child instanceof Element)
        {
            //cast a child to Element  
            Element element = (Element) child;
          
            //get the name of the child (element)         
            String childName=element.getTagName();
          
          
            System.out.println("current element "+childName);
            //get the content of the current element
            Text content = (Text) child.getFirstChild();
            String string3=content.getData().trim();
          
          
            System.out.println("content "+string3);
            //Get attributes of the current child
            NamedNodeMap attributes=child.getAttributes();
          
            for(int j=0;j<attributes.getLength();j++)
            {
                Node attribute=attributes.item(j);
                if(!(attribute instanceof Node) )
                    continue;
                String attributeName=attribute.getNodeName();
                String attributeValue=attribute.getNodeValue();
                          
                System.out.println("att "+attributeName+" = "+attributeValue);
            }//~attributes
          
        }//~if a child is element
    }//~children
  
} catch (ParserConfigurationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (SAXException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
  

}
public static void main(String[] args) {
    Test t=new Test();
    t.test();
}
}

Templates pour Eclipse (Servez-vous)


J'ai préparé quelques instructions XML, sous forme de templates pour Eclipse, vous permettant d'avoir un peu d'automatisme pour travailler avec des fichiers XML. Les templates sont encore en phase Beta (désolé).Je vais mettre les commentaire en Français prochainement.
Pour utiliser ces templates. Un clic sur le menu "Download" du site. Téléchargez le fichier .zip. Décompressez ce fichier.
Importez le fichier xml dans Eclipse. Dans un éditeur java tappez xml -> puis CTRL+ESPACE. Sélectionnez un template pour l'insérer dans le code.

Read more...

XML Parsing in Java part 1

Using the DOM parser provided with the Java SDK (nothing to install)

Structure of XML Documents
Any XML document has elements and text.

Three essential components
1.Header
2.Root element
3.Child elements

The root element can have one or more child element, and child element can have a child element or a text or both.

XML elements can have attributes.

XML Header
<?xml version="1,0" encoding="UTF-8"?>

An example an Eclipse template
The root element is <templates> and every template is inside <template> and </template>
These are child elements of the root. Elements have attributes (key/value), like autoinsert and a text (the content of the template)

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<templates>
    <template autoinsert="true" context="catchblock_context" deleted="false"     description="Code in new catch blocks" enabled="true"     id="org.eclipse.jdt.ui.text.codetemplates.catchblock" name="catchblock">
    // ${todo} Auto-generated catch block
    ${exception_var}.printStackTrace();</template>
</templates>

What is a parser?
A parser is a program that reads an XML file, verify it structure and get it's elements

Java library parsers

  • DOM parser -> reads a document into a tree structure
  • SAX parser -> produces events with XML elements

How to use the DOM parser included in the JDK

1-Get a DocumentBuilder object, using a DocumentBuilderFactory
 
DocumentBuilderFactory     documentBuilderFactory=DocumentBuilderFactory.newInstance();
  DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder();

2-Pass a File object (you can use a URL) to DocumentBuilder object to get a reference to the document :

  File file=new File("fileName");
  Document document=documentBuilder.parse(file);

3-With a reference to the Document you can get (Node objects):
  -The root element
  -Child elements
  -Content and attributes of elements

Elements can have name, attributes, text, etc...

4-Get the root
  Element root=document.getDocumentElement();

5-Get children
  //NodeList is a collection of Nodes
    NodeList children = root.getChildNodes();
    for (int i = 0; i < children.getLength(); i++)
    {
      
    Node child = children.item(i);
    //get rid of white spaces
    if(child instanceof Element)
     {
        ...
        ...
     }//~if a child is element
    }//~children

6-Get attributes
  NamedNodeMap attributes=child.getAttributes();
          
  for(int j=0;j<attributes.getLength();j++)
    {
    Node attribute=attributes.item(j);
    if(!(attribute instanceof Node) )
        continue;
    String attributeName=attribute.getNodeName();
    String attributeValue=attribute.getNodeValue();
              
    }//~attributes

7-More operations
  You can :
  - Get the name of an element : getTagName()
  - Get an attribute node by name : getAttributeNode(String name)
  - Remove an attribute by name : removeAttribute(String name)
  See the Javadoc for more details

Here is a demonstration program
package com.java_javafx.ka;

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.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;

/*
@author Kaesar ALNIJRES
*/

public class Test {
public void test()
{
//parse a file, get root element, children elements and their attributes

try {
    //prepare to read the xml document, by getting a DocumentBuilder
    DocumentBuilderFactory     documentBuilderFactory=DocumentBuilderFactory.newInstance();
    DocumentBuilder      documentBuilder=documentBuilderFactory.newDocumentBuilder();
    File file=new File("put_a_path_to_xml_file");
    Document document=documentBuilder.parse(file);
  
    //get the root element
    Element root=document.getDocumentElement();
  
    //get the root's name
    String string2=root.getTagName();
  
    System.out.println("root "+string2);
  
    //get a list of children
    NodeList children = root.getChildNodes();
    for (int i = 0; i < children.getLength(); i++)
    {
      
        Node child = children.item(i);
        //no white spaces
        if(child instanceof Element)
        {
            //cast a child to Element  
            Element element = (Element) child;
          
            //get the name of the child (element)         
            String childName=element.getTagName();
          
          
            System.out.println("current element "+childName);
            //get the content of the current element
            Text content = (Text) child.getFirstChild();
            String string3=content.getData().trim();
          
          
            System.out.println("content "+string3);
            //Get attributes of the current child
            NamedNodeMap attributes=child.getAttributes();
          
            for(int j=0;j<attributes.getLength();j++)
            {
                Node attribute=attributes.item(j);
                if(!(attribute instanceof Node) )
                    continue;
                String attributeName=attribute.getNodeName();
                String attributeValue=attribute.getNodeValue();
                          
                System.out.println("att "+attributeName+" = "+attributeValue);
            }//~attributes
          
        }//~if a child is element
    }//~children
  
} catch (ParserConfigurationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (SAXException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
  

}
public static void main(String[] args) {
    Test t=new Test();
    t.test();
}
}

Eclipse templates ready to use
I've prepared the very first version of an Eclipse template to parse an xml file. You can find it in the download section of this site.
Import the xml file into Eclipse. In a java editor type xml -> use CTRL+SPACE bar, use one of the templates.

Read more...

  © Blogger template Simple n' Sweet by Ourblogtemplates.com 2009

Back to TOP