Java XML Node Value setText(Element parent, String text)

Here you can find the source of setText(Element parent, String text)

Description

removes all element/text children, then adds a new single text child

License

Common Public License

Declaration

public static Text setText(Element parent, String text) 

Method Source Code


//package com.java2s;
/*//from   ww  w .j av  a2 s  . co  m
 * ====================================================================
 * This software is subject to the terms of the Common Public License
 * Agreement, available at the following URL:
 *   http://www.opensource.org/licenses/cpl.html .
 * Copyright (C) 2003-2004 TONBELLER AG.
 * All Rights Reserved.
 * You must accept the terms of that agreement to use this software.
 * ====================================================================
 *
 * 
 */

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

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

public class Main {
    /** removes all element/text children, then adds a new single text child */
    public static Text setText(Element parent, String text) {
        removeChildNodesExceptAttributes(parent);
        Document doc = parent.getOwnerDocument();
        Text child = doc.createTextNode(text);
        parent.appendChild(child);
        return child;
    }

    /**
     * removes all children of element ant text type
     */
    public static void removeChildNodesExceptAttributes(Element parent) {
        List v = getChildNodesExceptAttributes(parent);
        Iterator en = v.iterator();
        while (en.hasNext())
            parent.removeChild((Node) en.next());
    }

    /**
     * returns List of all direct child elements exept Attribute nodes.
     * Among others this will contain Element nodes and Text children.
     */
    public static List getChildNodesExceptAttributes(Node parent) {
        ArrayList retVec = new ArrayList();
        NodeList children = parent.getChildNodes();
        for (int i = 0; i < children.getLength(); ++i) {
            if (children.item(i).getNodeType() == Node.TEXT_NODE
                    || children.item(i).getNodeType() == Node.ELEMENT_NODE) {
                retVec.add(children.item(i));
            }
        }
        return retVec;
    }
}

Related

  1. getValueByTagName(Node n, String tag)
  2. getValueOfValueNode(Node n)
  3. getValues(Node metric)
  4. nodeToDouble(Node node)
  5. putAll(final NamedNodeMap dst, final NamedNodeMap src)
  6. setText(Element parentNode, String data)
  7. setText(Node n, String text)
  8. setText(Node node, String text)
  9. setText(Node node, String text)