Java tutorial
//package com.java2s; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** * Set the text content of an element. All exisitng Text Node are * removed before adding a new Text Node containing the given text. * * @param element target element to set text content, cannot be null. * @param text content of the element, cannot be null. */ public static void setElementText(Element element, String text) { // Remove all text element NodeList list = element.getChildNodes(); int len = list.getLength(); for (int i = 0; i < len; i++) { Node n = list.item(i); if (n.getNodeType() == Node.TEXT_NODE) { element.removeChild(n); } } Node child = element.getFirstChild(); Node textnode = element.getOwnerDocument().createTextNode(text); // insert text node as first child if (child == null) { element.appendChild(textnode); } else { element.insertBefore(textnode, child); } } }