Java XML Child Node Get getChildNodes(Node node)

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

Description

Helper method to get a list of only Text and Element typed Node s.

License

Apache License

Parameter

Parameter Description
node the node whose children to get

Return

the filtered list of child nodes

Declaration

private static List<Node> getChildNodes(Node node) 

Method Source Code

//package com.java2s;
/**/* w  w w.j  a v a2  s  .c  om*/
 * Copyright 2012 Comcast Cable Communications Management, LLC
 *
 * 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 java.util.ArrayList;

import java.util.List;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

public class Main {
    /**
     * Helper method to get a list of only {@link Text} and {@link Element} typed {@link Node}s.
     * This is partially to workaround the difficulty of working with the {@link NodeList} object.
     * 
     * @param node
     *            the node whose children to get
     * 
     * @return the filtered list of child nodes
     */
    private static List<Node> getChildNodes(Node node) {
        List<Node> children = new ArrayList<Node>();
        NodeList nl = node.getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            Node child = nl.item(i);
            short type = child.getNodeType();
            if (type == Node.ELEMENT_NODE) {
                children.add(child);
            } else if (type == Node.TEXT_NODE) {
                String text = ((Text) child).getTextContent().trim();
                if (text.length() > 0) {
                    children.add(child);
                }
            }
        }
        return children;
    }
}

Related

  1. getChildNodes(final Node node)
  2. getChildNodes(final Node node, final short nodetype)
  3. getChildNodes(final Node node, final String attributeName, final String value)
  4. getChildNodes(final Node node, short... types)
  5. getChildNodes(final Node parent, boolean recursiveSearch, final String... nodeNames)
  6. getChildNodes(Node node)
  7. getChildNodes(Node node)
  8. getChildNodes(Node node, short type)
  9. getChildNodes(Node node, String name)