Ajout et suppression de nodes dasn un fichier XML

cs_dragon Messages postés 2336 Date d'inscription samedi 14 juillet 2001 Statut Membre Dernière intervention 5 mai 2009 - 2 mai 2003 à 17:19
tellaw Messages postés 4 Date d'inscription mercredi 27 août 2003 Statut Membre Dernière intervention 18 juin 2004 - 18 juin 2004 à 23:46
je suis pas désespéré, mais je cherche comment ajouter et supprimer des nodes dans un fichiers XML

voici ma class XML:

package tp3;

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
// For write operation
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

/************************************************************
 * Title: EarthWorm Jim

                              *
 * Description: TP3 pour le cour de Java Graphique

   *
 * Copyright: Copyright (c) 2003

                     *
 * @author Maxime Savard                                    *
 * @version 1.0                                             *
 ************************************************************/

/************************************************************
 * Nom de la Classe : XML                                   *
 * Description : Permet de charger, de lire et de modifier  *
 *               un fichier XML                             *
 * extends : rien                                           *
 * implements : rien                                        *
 * utilise : le nom du fichier xml                          *
 ************************************************************/

public class XML {
  static Document document;
  private File f = null;
  public XML(String xml) {

    DocumentBuilderFactory factory =
        DocumentBuilderFactory.newInstance();

    try {
      f = new File(xml); //lecture du fichier

      DocumentBuilder builder = factory.newDocumentBuilder();
      document = builder.parse(f);

    }
    catch (SAXParseException spe) {
      // erreur fait par el parsing
      System.out.println("\n** Parsing erreur"
                         + ", line " + spe.getLineNumber()
                         + ", uri " + spe.getSystemId());
      System.out.println("   " + spe.getMessage());

      // Use the contained exception, if any
      Exception x = spe;
      if (spe.getException() != null) {
        x = spe.getException();
      }
      x.printStackTrace();

    }
    catch (SAXException sxe) {
      // erreur généré apr l'application
      Exception x = sxe;
      if (sxe.getException() != null) {
        x = sxe.getException();
      }
      x.printStackTrace();

    }
    catch (ParserConfigurationException pce) {
      // Parser with specified options can't be built
      pce.printStackTrace();

    }
    catch (IOException ioe) {
      // I/O error
      ioe.printStackTrace();
    }
  }

  /****************************************************************************
 * nom : getNode
 * commentaire : recevoir une node
 * recoi : nom de la node rechercher
 * renvoi : la node rechercher
 ****************************************************************************/

  public Node[] getNode(String node) {
    Node[] temp = null;
    int j = 0;
    // recevoir les nodes
    NodeList list = document.getElementsByTagName(node);
    temp = new Node[list.item(0).getChildNodes().getLength()];
    //lire les enfants
    for (int i = 1; i < list.item(0).getChildNodes().getLength(); i += 2) {
      if (list.item(0).getChildNodes().item(i).getChildNodes().item(0) != null) {
        temp[i] = list.item(0).getChildNodes().item(i).getChildNodes().item(0);
        ++j;
      }
    }
    Node[] temp2 = new Node[j];
    j = 0;
    //enlever les espaces
    for (int i = 0; i < list.item(0).getChildNodes().getLength(); ++i) {
      if (temp[i] != null) {
        temp2[j] = temp[i];
        ++j;
      }
    }

    return (temp2);

  }

  /****************************************************************************
 * nom : setNode
 * commentaire : met à jour une node
 * recoi : node rechercher, nom de la valeur à modifier, nouvelle valeur
 * renvoi : réussite
 ****************************************************************************/

  public boolean setNode(String node, String nom, String valeur) {
    Node temp = null;
    // lire les enfants et modifier
    try {
      NodeList list = document.getElementsByTagName(node);
      for (int i = 1; i < list.item(0).getChildNodes().getLength(); i += 2) {
        if (list.item(0).getChildNodes().item(i).getChildNodes().item(0) != null) {
          temp = list.item(0).getChildNodes().item(i).getChildNodes().item(0);
          if (temp.getParentNode().getNodeName().compareToIgnoreCase(nom) == 0) {
            temp.setNodeValue(valeur);
          }
        }
      }
      return true;
    }
    catch (Exception ex) {
      return false;
    }
  }

  /****************************************************************************
 * nom : miseAJour
 * commentaire : met à jour le fichier XML
 * recoi : rien
 * renvoi : réussite
 ****************************************************************************/

  public boolean miseAJour() {
    try {
      // mettre a jour
      TransformerFactory tFactory =
          TransformerFactory.newInstance();
      Transformer transformer = tFactory.newTransformer();

      DOMSource source = new DOMSource(document);
      //afficher dans le fichier
      StreamResult result = new StreamResult(f);
      transformer.transform(source, result);
      return true;

    }
    catch (TransformerConfigurationException tce) {
      // Error generated by the parser
      System.out.println("\n** Transformer Factory erreur");
      System.out.println("   " + tce.getMessage());

      // Use the contained exception, if any
      Throwable x = tce;
      if (tce.getException() != null) {
        x = tce.getException();
      }
      x.printStackTrace();
      return false;

    }
    catch (TransformerException te) {
      // Error generated by the parser
      System.out.println("\n** Transformation erreur");
      System.out.println("   " + te.getMessage());

      // Use the contained exception, if any
      Throwable x = te;
      if (te.getException() != null) {
        x = te.getException();
      }
      x.printStackTrace();
      return false;
    }

  }

  /****************************************************************************
 * nom : MontrerTout
 * commentaire : montrer tout dasn la console
 * recoi : rien
 * renvoi : rien
 ****************************************************************************/

  public void MontrerTout() {
    try {
      // lecture du fichier
      TransformerFactory tFactory =
          TransformerFactory.newInstance();
      Transformer transformer = tFactory.newTransformer();

      DOMSource source = new DOMSource(document);
      //afficher
      StreamResult result = new StreamResult(System.out);
      transformer.transform(source, result);

    }
    catch (TransformerConfigurationException tce) {
      // Error generated by the parser
      System.out.println("\n** Transformer Factory error");
      System.out.println("   " + tce.getMessage());

      // Use the contained exception, if any
      Throwable x = tce;
      if (tce.getException() != null) {
        x = tce.getException();
      }
      x.printStackTrace();

    }
    catch (TransformerException te) {
      // Error generated by the parser
      System.out.println("\n** Transformation error");
      System.out.println("   " + te.getMessage());

      // Use the contained exception, if any
      Throwable x = te;
      if (te.getException() != null) {
        x = te.getException();
      }
      x.printStackTrace();
    }
  }

  /****************************************************************************
 * nom : nomParent
 * commentaire : renvoi le parent en String
 * recoi : node rechercher
 * renvoi : nom
 ****************************************************************************/

  public String nomParent(Node node) {
    return node.getParentNode().getNodeName();
  }

  /****************************************************************************
 * nom : StringValeur
 * commentaire : renvoi la veleur en string
 * recoi : node rechercher
 * renvoi : valeur en string
 ****************************************************************************/

  public String StringValeur(Node node) {
    return ( (Object) node).toString();
  }

  /****************************************************************************
 * nom : IntValeur
 * commentaire : renvoi la valeur en int
 * recoi : node rechercher
 * renvoi : valeur en int
 ****************************************************************************/

  public int IntValeur(Node node) {
    try {
      int temp = Integer.parseInt(this.StringValeur(node));
      return temp;
    }
    catch (NumberFormatException ex) {
      return 0;
    }
  }
}

1 réponse

tellaw Messages postés 4 Date d'inscription mercredi 27 août 2003 Statut Membre Dernière intervention 18 juin 2004
18 juin 2004 à 23:46
Le plus simple ce n'est pas d'utiliser Xalan qui fait deja toutes ces fonctions ?

Tellaw@tellaw.org
0
Rejoignez-nous