Set the value of XML element - Java XML

Java examples for XML:XML Element Value

Description

Set the value of XML element

Demo Code


//package com.java2s;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    /**/*from w w w  .  ja va  2s  . co m*/
     * Set the value of element
     *
     * @param element
     * @param val
     */
    public static void setElementValue(Element element, String val) {
        Node node = element.getOwnerDocument().createTextNode(val);
        NodeList nl = element.getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            Node nd = nl.item(i);
            if (nd.getNodeType() == Node.TEXT_NODE) {
                nd.setNodeValue(val);
                return;
            }
        }
        element.appendChild(node);
    }
}

Related Tutorials