Java XML Node Normalize normalize(Node node)

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

Description

Trim all new lines from text nodes.

License

Apache License

Parameter

Parameter Description
node a parameter

Declaration

public static void normalize(Node node) 

Method Source Code

//package com.java2s;
/*//from  www  .ja v a2s . co m
 * 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);
    }
}

Related

  1. normalize(Node node)
  2. normalize(Node node)