Java tutorial
//package com.java2s; /* * Copyright 2001-2004 The Apache Software Foundation. * * 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.Node; import org.w3c.dom.Text; public class Main { /** * Trim all new lines from text nodes. * * @param node */ public static void normalize(Node node) { if (node.getNodeType() == Node.TEXT_NODE) { String data = ((Text) node).getData(); if (data.length() > 0) { char ch = data.charAt(data.length() - 1); if (ch == '\n' || ch == '\r' || ch == ' ') { String data2 = trim(data); ((Text) node).setData(data2); } } } for (Node currentChild = node.getFirstChild(); currentChild != null; currentChild = currentChild .getNextSibling()) { normalize(currentChild); } } public static String trim(String str) { if (str.length() == 0) { return str; } if (str.length() == 1) { if ("\r".equals(str) || "\n".equals(str)) { return ""; } else { return str; } } int lastIdx = str.length() - 1; char last = str.charAt(lastIdx); while (lastIdx > 0) { if (last != '\n' && last != '\r' && last != ' ') break; lastIdx--; last = str.charAt(lastIdx); } if (lastIdx == 0) return ""; return str.substring(0, lastIdx); } }