Ajout d'un élément dans un fichier xml
Bonjour, je souhaiterai écrire un code pour pouvoir ajouter de nouveaux éléments dans mon fichier xml.
Voici mon fichier xml :
Code:
1 2 3 4 5 6
| <MRacine>
<type valeur="">
<intitule/>
<couleur/>
</type>
</MRacine> |
Je souhaiterai ajouter un élément "nouveau" entre les balises <type>, au meme titre que intitule et couleur.
Voici mon code :
Code:
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
| public class testAjout{
static org.jdom.Document document;
static Element racine;
static Element type;
public static void main (String[] args){
try{
lireFichier("G:\\test.xml");
addElement("nouveau");
enregistreFichier("G:\\test3.xml");
}
catch(Exception e){}
}
static void lireFichier(String fichier) throws Exception{
SAXBuilder sxb = new SAXBuilder();
document = sxb.build(new File(fichier));
racine = document.getRootElement();
}
static void addElement(String element){
racine.addContent(type);
Element nouveau1=new Element ("nouveau");
type.addContent(nouveau1);
}
static void enregistreFichier(String fichier) throws Exception
{
XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
sortie.output(document, new FileOutputStream(fichier));
}
} |
Mais ça ne fait rien. Qu'est-ce qui ne va pas ?