Here you can find the source of getText(Node node)
Parameter | Description |
---|---|
node | a DOM node |
public static String getText(Node node)
//package com.java2s; /******************************************************************************* * Copyright (c) 2015 UNIT Information Technologies R&D Ltd * 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.j a v a 2 s. c o m * Ferhat Erata - initial API and implementation * H. Emre Kirmizi - initial API and implementation * Serhat Celik - initial API and implementation * U. Anil Ozturk - initial API and implementation *******************************************************************************/ import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** * Return the text that a node contains. This routine: * <ul> * <li>Ignores comments and processing instructions. * <li>Concatenates TEXT nodes, CDATA nodes, and the results of recursively processing EntityRef * nodes. * <li>Ignores any element nodes in the sublist. (Other possible options are to recurse into * element sublists or throw an exception.) * </ul> * * @param node a DOM node * @return a String representing its contents */ public static String getText(Node node) { StringBuffer result = new StringBuffer(); if (!node.hasChildNodes()) return ""; NodeList list = node.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node subnode = list.item(i); if (subnode.getNodeType() == Node.TEXT_NODE) { result.append(subnode.getNodeValue()); } else if (subnode.getNodeType() == Node.CDATA_SECTION_NODE) { result.append(subnode.getNodeValue()); } else if (subnode.getNodeType() == Node.ENTITY_REFERENCE_NODE) { // Recurse into the subtree for text // (and ignore comments) result.append(getText(subnode)); } } return result.toString(); } }