Java examples for XML:XML Node Text
This will trim trailing and leading white space from a Text node in a DOM structure.
//package com.java2s; import org.w3c.dom.*; public class Main { /**// w w w .j a v a 2 s.c o m * This will trim trailing and leading white space from a Text * node in a DOM structure. * * @return java.lang.String * @param textNode org.w3c.dom.Text */ public static String trim(Text textNode) { String text = textNode.getNodeValue(); if (null == text) return ""; char[] array = text.toCharArray(); int length = array.length; if (0 == length) return ""; // Strip leading white space int start = 0; boolean isWhite = Character.isWhitespace(array[start]); while (isWhite) { ++start; if (start >= length) return ""; // It was all white isWhite = Character.isWhitespace(array[start]); } // Strip trailing white space int end = length - 1; isWhite = Character.isWhitespace(array[end]); while (isWhite) { --end; if (end <= 0) return ""; // It was all white isWhite = Character.isWhitespace(array[end]); } // If we get here, we had some non-whitespace return new String(array, start, end - start + 1); } }