Java XML Element Set setText(Element e, String text)

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

Description

Set the text of the specified element to the given string.

License

Open Source License

Parameter

Parameter Description
e The element.
text The text string.

Declaration

public static void setText(Element e, String text) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2012 Firestar Software, Inc.
 * 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:/*from   w  w  w  .j a  v a2  s. co m*/
 *     Firestar Software, Inc. - initial API and implementation
 *
 * Author:
 *     Gabriel Oancea
 *
 *******************************************************************************/

import org.w3c.dom.*;

public class Main {
    /**
     * Set the text of the specified element to the given string.
     * 
     * @param e The element.
     * @param text The text string.
     */
    public static void setText(Element e, String text) {
        NodeList lst = e.getChildNodes();
        int size = lst.getLength();
        for (int i = 0; i < size; i++) {
            Node n = lst.item(i);
            if (n.getNodeType() == Node.TEXT_NODE) {
                Text t = (Text) n;
                t.setData(text.trim());
                return;
            }
        }
        Document doc = e.getOwnerDocument();
        // bit of a hack - we preserve the cdata on the way in so we can serialize correctly
        // This only works on xml to xml 
        // TODO need to have a "preserve format" or some such on the mdmi structure
        if (text.startsWith("<![CDATA[") && text.endsWith("]]>")) {
            CDATASection cdata = doc.createCDATASection(text != null ? text
                    .substring(9, text.lastIndexOf("]]>")) : null);
            e.appendChild(cdata);
        } else {
            Text txt = doc
                    .createTextNode(text != null ? text.trim() : null);
            e.appendChild(txt);
        }

    }
}

Related

  1. setProperty(Element element, BeanDefinitionBuilder bean, String name)
  2. setText(Element elem, String value)
  3. setText(Element element, String data)
  4. setText(Element element, String text)
  5. setText(Element element, String text)