Java XML Node Text Value getRawContent(Node n)

Here you can find the source of getRawContent(Node n)

Description

Get the raw text content of a node or null if there is no text

License

Apache License

Declaration

public static String getRawContent(Node n) 

Method Source Code

//package com.java2s;
/**/*  w  w  w. j a  v a2  s.c  o m*/
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you 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 {
    /**
     * Get the raw text content of a node or null if there is no text
     */
    public static String getRawContent(Node n) {
        if (n == null) {
            return null;
        }
        StringBuilder b = null;
        String s = null;
        Node n1 = n.getFirstChild();
        while (n1 != null) {
            if (n1.getNodeType() == Node.TEXT_NODE) {
                if (b != null) {
                    b.append(((Text) n1).getNodeValue());
                } else if (s == null) {
                    s = ((Text) n1).getNodeValue();
                } else {
                    b = new StringBuilder(s).append(((Text) n1).getNodeValue());
                    s = null;
                }
            }
            n1 = n1.getNextSibling();
        }
        if (b != null) {
            return b.toString();
        }
        return s;
    }
}

Related

  1. getNormalizedText(Node node)
  2. getPlainTextBelow(Node n)
  3. getPropertiesFromXML(Node propNode)
  4. getPropertiesFromXML(Node propNode)
  5. getPropText(Node node)
  6. getSimpleElementText(final Node node)
  7. getSimpleNodeValue(Node node)
  8. getSingleNodeTextContent(Node node, String path)
  9. getStrElementValue(Node node)