Here you can find the source of getTextBetween(Node node1, Node node2)
Parameter | Description |
---|---|
node1 | Test node. |
public static String getTextBetween(Node node1, Node node2)
//package com.java2s; /*//from w ww. ja v a 2s .c o m * ePUB Corrector - https://github.com/vysokyj/epub-corrector/ * * Copyright (C) 2012 Jiri Vysoky * * ePUB Corrector is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * ePUB Corrector is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Cobertura; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ import org.w3c.dom.*; public class Main { /** * Get all the text DOM sibling nodes before the supplied node and * concatenate them together into a single String. * * @param node1 Test node. * @return String containing the concatentated text. */ public static String getTextBetween(Node node1, Node node2) { Node parent1 = node1.getParentNode(); if (parent1 == null) { System.out.println("Cannot get text between nodes [" + node1 + "] and [" + node2 + "]. [" + node1 + "] has no parent."); return ""; } Node parent2 = node2.getParentNode(); if (parent2 == null) { System.out.println("Cannot get text between nodes [" + node1 + "] and [" + node2 + "]. [" + node2 + "] has no parent."); return ""; } if (parent1 != parent2) { System.out.println("Cannot get text between nodes [" + node1 + "] and [" + node2 + "]. These nodes do not share the same sparent."); return ""; } NodeList siblings = parent1.getChildNodes(); StringBuffer text = new StringBuffer(); boolean append = false; int siblingCount = siblings.getLength(); for (int i = 0; i < siblingCount; i++) { Node sibling = siblings.item(i); if (sibling == node1) { append = true; } if (sibling == node2) { break; } if (append && sibling.getNodeType() == Node.TEXT_NODE) { text.append(((Text) sibling).getData()); } } return text.toString(); } }