Re: creer une balise en java a un endroit precis

Herve AGNOUX <[email protected]>
Newsgroups gmane.text.xml.french.tech
Organization SARL diaam informatique
Message-ID <[email protected]>
Le Lundi 20 Mars 2006 16:56, [email protected] a écrit :
>
> Quelqu'un aurait il une suggestion ?
>

Il faut utiliser Node.insertBefore.

Voici un exemple ; pardonnez le coté un peu expéditif des choses.

/*
 * CreerUneBaliseEnJavaEnUnEndroitPrecis.java
 *
 * Created on 21 mars 2006, 08:07
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package village;

import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 *
 * @author herve
 */
public class CreerUneBaliseEnJavaEnUnEndroitPrecis
{
  public static void main(String[] args) throws Exception
  {
    DocumentBuilderFactory fabriqueDeConstructeur;
    DocumentBuilder db;
    StringReader xml;
    Document un;
    NodeList filstest;
    Element root;
    Element quatrième;
    Element nouveauA;
    DOMSource source;
    StreamResult resultat;
    StringWriter caracteresxmlresultat;
    
    // on construit le Document DOM que l'on place dans "un".
    fabriqueDeConstructeur = DocumentBuilderFactory.newInstance();
    fabriqueDeConstructeur.setNamespaceAware(true);
    db = fabriqueDeConstructeur.newDocumentBuilder();
    xml = new StringReader(
            "<test>"+
            "<test_1/>"+
            "<test_2/>"+
            "<test_3/>"+
            "<test_4/>"+
            "<test_5/>"+
            "</test>");
    un = db.parse(new InputSource(xml));
    
    // on insère le bon élément à la bonne place.
    root = un.getDocumentElement();
    filstest = root.getChildNodes();
    quatrième = (Element)filstest.item(3);
    nouveauA = un.createElement("test_A");
    root.insertBefore(nouveauA, quatrième);
    
    // et on affiche le résultat, en toute simplicité et facilité.
    caracteresxmlresultat = new StringWriter();
    source = new DOMSource(un);
    resultat = new StreamResult(caracteresxmlresultat);
    TransformerFactory.newInstance().newTransformer().transform(
            source, resultat);
    System.out.println("Enjoy : "+caracteresxmlresultat.toString());
  }
}


Cordialement.


-- 
SARL diaam informatique - 04 77 25 43 28
Ingenierie, développements de systèmes d'information
http://www.diaam-informatique.com
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.