1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| //Créer une nouvelle 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
{
static org.jdom.Document document;
static Element racine;
public static void main(String[] args)
{
try
{
lireFichier("xml.xml");
supprElement("curve");
enregistreFichier("xmls.xml");
}
catch(Exception e){}
}
//On parse le fichier et on initialise la racine de
//notre arborescence
static void lireFichier(String fichier) throws Exception
{
SAXBuilder sxb = new SAXBuilder();
document = sxb.build(new File(fichier));
racine = document.getRootElement();
}
//On fait des modifications sur un Element
static void supprElement(String element)
{
//Dans un premier temps on liste tous les étudiants
List listEtudiant = racine.getChildren("form");
Iterator i = listEtudiant.iterator();
//On parcours la liste grâce à un iterator
while(i.hasNext())
{
Element courant = (Element)i.next();
//Si l'etudiant possède l'Element en question on applique
//les modifications.
if(courant.getChild(element)!=null)
{
//On supprime l'Element en question
courant.removeChild(element);
//On renomme l'Element père sachant qu'une balise XML n'accepte
//ni les espaces ni les caractères spéciaux
//"etudiant modifié" devient "etudiant_modifie"
courant.setName("etudiant_modifie");
}
}
}
//On enregsitre notre nouvelle arborescence dans le fichier
//d'origine dans un format classique.
static void enregistreFichier(String fichier) throws Exception
{
XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
sortie.output(document, new FileOutputStream(fichier));
}
} |
Partager