Java XML Node Text Value getText(Node node)

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

Description

get Text

License

Open Source License

Declaration

public static String getText(Node node) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 *     Copyright (c) 2006-2010 eBay Inc. All Rights Reserved.
 *     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 
 *    /*from w  w w .  jav a 2s  .co  m*/
 *        http://www.apache.org/licenses/LICENSE-2.0
 *******************************************************************************/

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

public class Main {
    public static String getText(Node node) {
        StringBuffer result = new StringBuffer();
        NodeList nodes = node.getChildNodes();
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node2 = nodes.item(i);
            if (node2.getNodeType() == Node.TEXT_NODE || node2.getNodeType() == Node.CDATA_SECTION_NODE) {
                String value = node2.getNodeValue();
                result.append(value);
            }
        }
        return result.toString().trim();
    }

    /**
     * Get value of a given node.
     */
    public static String getNodeValue(final Element node) {
        if (node == null)
            return null;
        final String result = node.getNodeValue();
        if (result != null)
            return result;

        final NodeList list = node.getChildNodes();
        if (list == null || list.getLength() == 0)
            return null;
        final StringBuffer buff = new StringBuffer();
        boolean counter = false;

        for (int k = 0, listCount = list.getLength(); k < listCount; k++) {
            final Node child = list.item(k);
            if (child.getNodeType() == Node.TEXT_NODE || child.getNodeType() == Node.CDATA_SECTION_NODE) {
                buff.append(child.getNodeValue());
                counter = true;
            } else if (child.getNodeType() == Node.ENTITY_REFERENCE_NODE
                    || child.getNodeType() == Node.ENTITY_NODE) {
                final Node child2 = child.getFirstChild();
                if (child2 != null && child2.getNodeValue() != null)
                    buff.append(child2.getNodeValue());
                counter = true;
            }
        }

        if (counter == false)
            return null;
        return buff.toString();
    }
}

Related

  1. getText(Node node)
  2. getText(Node node)
  3. getText(Node node)
  4. getText(Node node)
  5. getText(Node node)
  6. getText(Node node)
  7. getText(Node node)
  8. getText(Node node)
  9. getText(Node node)