Java XML Node Text Value getTextValue(Node node)

Here you can find the source of getTextValue(Node node)

Description

Recursively scans all child elements, appending any text nodes.

License

Apache License

Declaration

public static String getTextValue(Node node) 

Method Source Code

//package com.java2s;
/*//from   www .ja va  2  s  .  c  om
 * $Header$
 * $Revision: 207706 $
 * $Date: 2004-08-30 16:08:10 +0800 (Mon, 30 Aug 2004) $
 *
 * ====================================================================
 *
 * Copyright 1999-2002 The Apache Software Foundation 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

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

public class Main {
    /**
     *  Recursively scans all child elements, appending any text nodes.
     *
     *  <PRE>
     *  &lt;customer&gt;Joe Schmoe&lt;/customer&gt;
     *  </PRE>
     *
     *  <P>  In this case, calling this method on the
     *  <CODE>customer</CODE> element returns "Joe Schmoe".
     */
    public static String getTextValue(Node node) {

        // I *thought* that I should be able to use element.getNodeValue()...

        StringBuffer text = new StringBuffer();
        NodeList nodeList = node.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            if (nodeList.item(i).getNodeType() == Node.TEXT_NODE
                    || nodeList.item(i).getNodeType() == Node.CDATA_SECTION_NODE) {
                text.append(((Text) nodeList.item(i)).getData());
            } else {
                text.append(getTextValue(nodeList.item(i)));
            }
        }
        return text.toString();
    }
}

Related

  1. getTextOfEl(Node e)
  2. getTextTrim(Node node)
  3. getTextValue(Node node)
  4. getTextValue(Node node)
  5. getTextValue(Node node)
  6. getTextValue(Node node)
  7. getTrimmedText (final Node node)
  8. getTrimmedTextContent(Node element)
  9. hasNodeText(Node n)