Java XML Node Text Value getTextBefore(Node node)

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

Description

Get all the text DOM sibling nodes before the supplied node and concatenate them together into a single String.

License

Open Source License

Parameter

Parameter Description
node Text node.

Return

String containing the concatentated text.

Declaration

public static String getTextBefore(Node node) 

Method Source Code


//package com.java2s;
/*//from  w  w w . j a v a2s. co  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 node Text node.
     * @return String containing the concatentated text.
     */
    public static String getTextBefore(Node node) {
        Node parent = node.getParentNode();
        if (parent == null) {
            System.out.println("Cannot get text before node [" + node + "]. [" + node + "] has no parent.");
            return "";
        }

        NodeList siblings = parent.getChildNodes();
        StringBuffer text = new StringBuffer();
        int siblingCount = siblings.getLength();

        for (int i = 0; i < siblingCount; i++) {
            Node sibling = siblings.item(i);

            if (sibling == node) {
                break;
            }
            if (sibling.getNodeType() == Node.TEXT_NODE) {
                text.append(((Text) sibling).getData());
            }
        }

        return text.toString();
    }
}

Related

  1. getText(Node node)
  2. getText(Node node)
  3. getText(Node node)
  4. getText(Node node)
  5. getText(Node node)
  6. getTextBetween(Node node1, Node node2)
  7. getTextBuffer(Node e, StringBuilder sb)
  8. getTextContent(final Node node)
  9. getTextContent(final Node node)