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

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

Description

Removes any existing child content and inserts a text node with the given text

License

Open Source License

Parameter

Parameter Description
element element to add text content to
text text to add as value

Exception

Parameter Description
DOMException an exception

Declaration

private static void setTextContent(Element element, String text) throws DOMException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2009, 2010 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors://w w w.  ja va2  s  .c  o  m
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/

import org.w3c.dom.*;

public class Main {
    /**
     * Removes any existing child content and inserts a text node with the given text
     * @param element element to add text content to
     * @param text text to add as value
     * @throws DOMException
     */
    private static void setTextContent(Element element, String text) throws DOMException {
        Node child;
        while ((child = element.getFirstChild()) != null) {
            element.removeChild(child);
        }
        if (text != null && text.length() > 0) {
            Text textNode = element.getOwnerDocument().createTextNode(text);
            element.appendChild(textNode);
        }
    }
}

Related

  1. setText(Element element, String text)
  2. setTextContent(Element elem, String content)
  3. setTextContent(Element elem, String value)
  4. setTextContent(Element element, String content)
  5. setTextContent(Element element, String content)
  6. setTextContent(Element node, String text)
  7. setTextContent(Element node, String text)
  8. setTextField(Element node, String subElement, String text)
  9. setTextValue(Element element, String text)