/***** Code de MesExemples.com *******/
/**
* @(#)XMLNouvelElement.java
*
*
* @author
*sakoba(java.mesexemples.com) @version 1.00 2013/7/4
*/
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
public class XMLNouvelElement {
public static void main (String[] args)throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("test.xml"));
Element element = doc.getDocumentElement();
addChildElement(element, "apprec", "welcom");
}
public static void addChildElement(Element element, String name, Object
textValue) {
Document document = element.getOwnerDocument();
Element child = document.createElement(name);
element.appendChild(child);
if (textValue != null) {
String text = textValue.toString();
child.appendChild(document.createTextNode(text));
}
}
}
Code testé avec le fichier XML Suivant
Sakoba
Adams
Rappel
Ne m'oubliez pas ce week-end!