/***** Code de MesExemples.com *******/
/**
* @(#)ReplaceNode.java
*
*
* @author
*sakoba(java.mesexemples.com) @version 1.00 2013/7/4
*/
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
public class ReplaceNode {
public void replacePerson(Document doc, String name,String phone,String
email) {
Element newPersonNode = doc.createElement("person");
Element nameNode = doc.createElement("name");
newPersonNode.appendChild(nameNode);
Text nametextNode = doc.createTextNode(name);
nameNode.appendChild(nametextNode);
Element phoneNode = doc.createElement("phone");
newPersonNode.appendChild(phoneNode);
Text phonetextNode = doc.createTextNode(phone);
phoneNode.appendChild(phonetextNode);
Element emailNode = doc.createElement("email");
newPersonNode.appendChild(emailNode);
Text emailtextNode = doc.createTextNode(email);
emailNode.appendChild(emailtextNode);
Element root = doc.getDocumentElement();
Element oldPersonNode = (Element)root.getFirstChild();
root.replaceChild(newPersonNode,oldPersonNode);
}
}
Code testé avec le fichier XML Suivant
Sakoba
Adams
Rappel
Ne m'oubliez pas ce week-end!