Java tutorial
//package com.java2s; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /*************************************************************************** * Sets the value of the first child under the given element with the given * name. If the child has no nodes, one is created. * * @param doc * @param e * @param name * @param value * @return * @throws Exception **************************************************************************/ public static boolean setChildValueByName(Document doc, Element e, String name, String value) throws Exception { NodeList childNodes = e.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node node = childNodes.item(i); if (node.getNodeType() != Node.ELEMENT_NODE) continue; if (node.getNodeName().equals(name)) { Node child = node.getFirstChild(); if (child == null) ((Element) node).appendChild(doc.createTextNode(value)); else child.setNodeValue(value); return true; } } return false; } }