Here you can find the source of getText(Node node)
Parameter | Description |
---|---|
node | A DOM node from which to extract text. |
public static String getText(Node node)
//package com.java2s; /*//from w ww . ja va 2s .c o m * Copyright 2003 Federal Chancellery Austria * MOA-ID has been developed in a cooperation between BRZ, the Federal * Chancellery Austria - ICT staff unit, and Graz University of Technology. * * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by * the European Commission - subsequent versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * http://www.osor.eu/eupl/ * * Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and * limitations under the Licence. * * This product combines work with different licenses. See the "NOTICE" text * file for details on the various modules and licenses. * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. */ 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> * <li>Concatenates TEXT nodes, CDATA nodes, and the results recursively * processing EntityRef nodes.</li> * <li>Ignores any element nodes in the sublist. (Other possible options are * to recurse into element sublists or throw an exception.)</li> * </ul> * * @param node A DOM node from which to extract text. * @return A String representing its contents. */ public static String getText(Node node) { if (!node.hasChildNodes()) { return ""; } StringBuffer result = new StringBuffer(); 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(); } }