Here you can find the source of getText(Element element)
Parameter | Description |
---|---|
element | the target element |
static public String getText(Element element)
//package com.java2s; /*-------------------------------------------------------------------------- * Copyright 2004 Taro L. Saito//from w ww .j a v a 2 s .c o m * * 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.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; public class Main { /** * Gets the text data enclosed by the specified element. If xml data has * several separated text data, the returned text will be their * concatination. For example, in the following XML data, * {@link #getText(Element)} for the wiki element gives " Hello World! Nice * to meet you.". * * <pre> * <wiki> * Hello World! * <author>leo</author> * Nice to meet you. * <wiki> * </pre> * * The result removes ignorable white spaces between tags. * * @param element * the target element * @return the text content of the element, or null if no text content is * found under the element */ static public String getText(Element element) { NodeList nodeList = element.getChildNodes(); StringBuilder buf = new StringBuilder(); int numTextNodes = 0; for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.TEXT_NODE) { if (!((Text) node).isElementContentWhitespace()) { numTextNodes++; buf.append(node.getNodeValue()); } } } return numTextNodes > 0 ? buf.toString() : null; } }