Java XML Element Set setTextValue(Element element, String text)

Here you can find the source of setTextValue(Element element, String text)

Description

Replace the first text element of the given element with a new text element containing the given text or just create a new text element if there is none to replace.

License

Apache License

Parameter

Parameter Description
element Element whose text element we want
text Text to set

Declaration


public static void setTextValue(Element element, String text) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

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

import org.w3c.dom.Node;

public class Main {
    /** Replace the first text element of the given element with a new
    text element containing the given text or just create a new text
    element if there is none to replace.
         //  www .  j a v a2 s .  c  o  m
    @param element Element whose text element we want 
    @param text Text to set */

    public static void setTextValue(Element element, String text) {
        Node newTextNode = element.getOwnerDocument().createTextNode(text);

        NodeList childs = element.getChildNodes();
        for (int i = 0; i < childs.getLength(); i++) {
            Node node = childs.item(i);
            if (Node.TEXT_NODE == node.getNodeType()) {
                element.replaceChild(newTextNode, node);
                return;
            }
        }
        element.appendChild(newTextNode);
    }
}

Related

  1. setTextContent(Element element, String content)
  2. setTextContent(Element element, String text)
  3. setTextContent(Element node, String text)
  4. setTextContent(Element node, String text)
  5. setTextField(Element node, String subElement, String text)
  6. setTextValue(Element element, String value)
  7. setToElements(Element rootElem, String name, Set s)
  8. setValue(Element element, String value)